[Chartjs]-How to make tool tip contents display on multiple lines

4👍

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

enter image description here


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/

Leave a comment