[Chartjs]-How to disable canvas elements from hijacking mouse wheel when scrolling through a page?

3πŸ‘

βœ…

If you are just using Chart.js, I don’t think Chart.js will hijack the wheel event. But if you use chartjs-plugin-zoom together, the wheel event will be hijacked.

(chartjs-plugin-zoom is a zoom and pan plugin for Chart.js)

chartjs-plugin-zoom hijacks mouse wheel when scrolling. If you would like the user to use mouse wheel to scroll up or down the page, instead of zooming in or out a chart, you can un-register the wheel event from the chart, as below:

var myChart = new Chart(ctx, {...});
myChart.ctx.canvas.removeEventListener('wheel', myChart._wheelHandler);

You can re-add the event handler whenever needed:

myChart.ctx.canvas.addEventListener('wheel', myChart._wheelHandler);

Check out this example on jsfiddle.

2πŸ‘

This is an example canvas:

canvas
{
  background-color: red;
}
<canvas></canvas>

Run the snippet and test it. You will see there is no scroll suppression at all.

What you experience is something Chart.js adds on purpose.

To remove it do, with jQuery, as follows:

$(function () {
  $("*").off("scroll");
});

This will remove all scroll handlers from all elements on the page, or a less aggressive way:

  $("canvas").off("scroll");

This last way is less aggressive and keeps non-canvases alone, but it may not suffice. The scroll handler may be attached to an ancestor of the canvas, such as a an invisible div.

2πŸ‘

To exclusively capture the event you could directly change the onmousewheel method of the element.

this.canvas.onmousewheel = function(evt){
    //perform your own Event dispatching here
    return false;
};

β€œ`

1πŸ‘

Config option in setup. This will disable the zoom plugin.

options: {
  plugins: {
    zoom: false
  }
}

Leave a comment