Blog>
Snippets

Handling Resizing and Events for Interactive Responsive Charts

Present a method for attaching resize event listeners to chart containers and debouncing these events for performance, alongside implementing interactive chart features such as tooltips.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}
This code creates a debounce function to limit the rate at which a function is executed. This is particularly useful for resizing event listeners to improve performance.
window.addEventListener('resize', debounce(function() {
    myChartInstance.resize();
}, 250));
Attaches a debounced resize event listener to the window. When the window is resized, it will wait for a pause of 250ms before resizing the chart. This prevents excessive calls to resize function and maintains performance.
var ctx = document.getElementById('myChart').getContext('2d');
var myChartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        tooltips: {
            mode: 'index',
            intersect: false,
        },
        hover: {
            mode: 'nearest',
            intersect: true
        }
    }
});
Initializes a responsive Chart.js chart with interactive tooltips. The chart listens for hover events to display tooltips, and it automatically resizes when its container does.