Capture Scrolling Events

I want to capture an event when the user scrolls their scroll wheel in a situation where the page does not scroll / does not scroll. However, the standard JS scroll event is fired only when the browser actually performs the scroll and will not fire the DOM element in which the overflow will be hidden.

Scrolling Google maps to enlarge is an example of the type of behavior I'm looking for.

Does anyone know how to do this?

Thanks.

+6
source share
3 answers

You can easily capture the mouse-wheel event:

$( '#yourElement' ).on( 'DOMMouseScroll mousewheel', function () { ... }); 

Live demo: http://jsfiddle.net/chtNP/1/

(I use jQuery to bind an event handler, but it works no matter which API you use, of course.)

+10
source

Firefox currently defines DOMMouseScroll events and wheels. Chrome, Opera and IE (last, again!) Define the mouse wheel.

Here is how I did it:

 if(window.onwheel !== undefined) { window.addEventListener('wheel', onMouseWheel) } else if(window.onmousewheel !== undefined) { window.addEventListener('mousewheel', onMouseWheel) } else { // unsupported browser } 

Note that addEventListener support in older versions of IE requires a polyfill. Alternatively, you can use the old window .mousewheel = function () {} or any other method.

As you can see, the event listener is attached to the window object. You cannot attach it to elements in a cross browser. You can use the target object property to see where it was called and make a filter based on it.

PS: Another cross-browser consideration: in IE you should use the "wheelDelta" property (and invert its sign!) Inside the event object when it is processed in the callback function ("onMouseWheel"). Other browsers will populate "deltaY" (or "deltaX" for horizontal scrolling).

+2
source

With jQuery, you can use this plugin or any number of similar ones that do the same.

If jQuery or a similar structure is not an option, maybe, but get ready for the world of pain when you want to make it work in multiple browsers ...

0
source

All Articles