[Chartjs]-Chart.js different x axis and tooltip format

22👍

First, you would better edit your chart properties directly from the options of the chart, and not in the scale service as you did so that it won’t affect every chart on your page (if you have several).

To achieve what you already did, add the function you used in your options :

options: {
    scales: {
        xAxes: [{
            ticks: {
                callback: function(tick) {
                    var characterLimit = 20;
                    if (tick.length >= characterLimit) {
                        return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';
                    }
                    return tick;
                }
            }
        }]
    },
}

It is basically an edit of what is displayed as labels on your xAxe.


However, we still have the same problem : both the labels and the tooltips display the trimmed string.

To fix it, you’ll also need to edit the callback of the tooltip :

options: {
    // other options here, `scales` for instance
    // ...
    tooltips: {
        callbacks: {

            // We'll edit the `title` string
            title: function(tooltipItem){
                // `tooltipItem` is an object containing properties such as
                // the dataset and the index of the current item

                // Here, `this` is the char instance

                // The following returns the full string
                return this._data.labels[tooltipItem[0].index];
            }
        }
    }
}

You can see a full example in this jsFiddle and here is its result :

enter image description here

Leave a comment