I'm using Chart.js and I can't seem to insert a line break into the tool tip text. I've tried \n, but that doesn't seem to work for me. How else should I go about doing this?
-
define width of tooltip which will force text to extend multiple lines – Muhammad Umer Jun 27 '15 at 22:24
-
Wait, how do you define the width of the tooltip @MuhammadUmer? – Ben Leitner Jun 27 '15 at 22:39
-
@Ben - what type of chart? (Line, Pie..) and single series or multiple series? – potatopeelings Jun 27 '15 at 23:30
-
@potatopeelings it's a single series bar chart. – Ben Leitner Jun 28 '15 at 00:03
1 Answers
Chart.js uses canvas fillText for the tooltips in it's default tooltip function. fillText unfortunately doesn't support word wrapping.
So you'll have to write your own custom tooltip function. There again, the labels are also used for the x axis. The easiest way would be to use \b (it's just ignored in your axis fillText) and swap it out in your custom tooltip function.
Preview
Code
var myLineChart = new Chart(ctx).Bar(data, {
customTooltips: function (tooltip) {
var tooltipEl = $('#chartjs-tooltip');
if (!tooltip) {
tooltipEl.css({
opacity: 0
});
return;
}
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split(":");
var re = new RegExp('\b', 'g');
var innerHtml = '<span>' + parts[0].trim().replace(re, '<br/>') + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html(innerHtml);
tooltipEl.css({
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle,
});
}
});
with the following markup added (your tooltip wrapper)
<div id="chartjs-tooltip"></div>
and the following CSS (for positioning your tooltip)
#chartjs-tooltip {
opacity: 0;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
padding: 3px;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, -120%);
transform: translate(-50%, -120%);
}
and your labels would look like
labels: ["Jan\bua\bry", "February", "Mar\bch", "April", "May", "June", "July"],
with \b standing for breaks. Note that you \n, \r, \t, \f... won't work if you don't want spaces in your x axis labels. If you actually want there to be spaces just use \n or something and change the RegEx accordingly
Fiddle - http://jsfiddle.net/5h1r71g8/

- 40,709
- 7
- 95
- 119