Peri Hartman Peri Hartman - 6 months ago 53
Javascript Question

javascript addEventListener "wheel" for element still scrolls window

I have the following javascript code, which triggers when a user wants to view a large image:

var divOverlay = document.getElementById ("overlay"); = "visible";
divOverlay.addEventListener ("wheel", zoom); // respond to mouse wheel

The function zoom() is working fine. It handles events from the mouse wheel and zooms in or out for the image, contained in "overlay".

The problem is that the mouse wheel events are also causing scrolling of the whole browser window. I want the mouse wheel events to go only to "overlay".

I have tried adding this:

origOnWheel = window.onwheel;
window.onwheel = function() { return false; }

followed, later, with restoring window.onWheel when the user is done. That partially works: it prevents the window from scrolling then the user is zooming "overlay". However, when the user finishes (and window.onWheel is restored), the main browser window no longer scrolls with the mouse wheel.

Answer Source

It will be a bit hard to give a complete (working) example without a working jsfiddle, but here are the guidelines:

  1. Inside the zoom function - when you want to prevent the regular scroll of the page - you should use event.preventDefault()
  2. You will need to decide if you want to disable the default scroll - basically this will be based on the height of the image vs. the height of the window (window.innerHeight). In case the height of the image is larger - you should not use the event.preventDefault() or do the prevent default and set the window.scrollTo(x, y) where the y should be the height of image - the height of the window (this will scroll to the bottom of the image).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download