[Chartjs]-How to navigate tooltips popup by clicking custom buttons outside Chart.js v2 canvas?

4👍

You can do this by utilizing the chart instance methods


Script

var myRadarChart = new Chart(ctx, {
    ...

(function (chart) {
    var helpers = Chart.helpers;

    var currentDatasetIndex;
    var currentPointIndex;

    $('#ChartV2').click(function (e) {
        // try getting an element close to the click
        var activePoints = chart.getElementAtEvent(e);
        var firstPoint = activePoints[0];

        if (firstPoint === undefined) {
            // otherwise pick the first visible element
            helpers.each(chart.data.datasets, function (dataset, datasetIndex) {
                if (firstPoint === undefined && this.isDatasetVisible(datasetIndex)) {
                    var meta = this.getDatasetMeta(datasetIndex);
                    firstPoint = meta.data[0];
                }
            }, chart);
        }

        // need this check as we may have 0 visible elements
        if (firstPoint !== undefined) {
            currentDatasetIndex = firstPoint._datasetIndex;
            currentPointIndex = firstPoint._index;
            $('#prev, #next').removeAttr('disabled');
            updateView();
        }
    });

    $('#prev').click(function () {
        // we add (n - 1) and do a modulo n to move one step back in an n element array.
        if (currentPointIndex === 0)
            currentDatasetIndex = (currentDatasetIndex + chart.data.datasets.length - 1) % chart.data.datasets.length;
        currentPointIndex = (currentPointIndex + chart.data.labels.length - 1) % chart.data.labels.length;
        updateView();
    });

    $('#next').click(function () {
        currentPointIndex = (currentPointIndex + 1) % chart.data.labels.length;
        if (currentPointIndex === 0)
            currentDatasetIndex = (currentDatasetIndex + 1) % chart.data.datasets.length;
        updateView();
    });


    // this (hoisted) function will update the text and show the tooltip
    function updateView() {
        $('#value').text(
            chart.data.datasets[currentDatasetIndex].label + ' : ' +
            chart.data.labels[currentPointIndex] + ' : ' +
            chart.data.datasets[currentDatasetIndex].data[currentPointIndex]);

        // we mess around with an internal variable here - this may not work with a new version
        chart.tooltip._active = [ chart.getDatasetMeta(currentDatasetIndex).data[currentPointIndex] ];
        chart.tooltip.update();
        chart.render();
    }

}(myRadarChart));

If you want this functionality only for small screens, just add a screen size check to the above chart click handler and hide the buttons and label using media queries.


Fiddle – http://jsfiddle.net/uxqL6rwf/

Leave a comment