Created
July 21, 2016 02:16
-
-
Save rob1121/58bfb8636898c1bd4642fa86f1e9d01a to your computer and use it in GitHub Desktop.
Mouse wheel programming in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author URL: http://adomas.org/javascript-mouse-wheel/ | |
*/ | |
/** This is high-level function. | |
* It must react to delta being more/less than zero. | |
*/ | |
function handle(delta) { | |
if (delta < 0) | |
…; | |
else | |
…; | |
} | |
/** Event handler for mouse wheel event. | |
*/ | |
function wheel(event){ | |
var delta = 0; | |
if (!event) /* For IE. */ | |
event = window.event; | |
if (event.wheelDelta) { /* IE/Opera. */ | |
delta = event.wheelDelta/120; | |
/** In Opera 9, delta differs in sign as compared to IE. | |
*/ | |
if (window.opera) | |
delta = -delta; | |
} else if (event.detail) { /** Mozilla case. */ | |
/** In Mozilla, sign of delta is different than in IE. | |
* Also, delta is multiple of 3. | |
*/ | |
delta = -event.detail/3; | |
} | |
/** If delta is nonzero, handle it. | |
* Basically, delta is now positive if wheel was scrolled up, | |
* and negative, if wheel was scrolled down. | |
*/ | |
if (delta) | |
handle(delta); | |
} | |
/** Initialization code. | |
* If you use your own event management code, change it as required. | |
*/ | |
if (window.addEventListener) | |
/** DOMMouseScroll is for mozilla. */ | |
window.addEventListener('DOMMouseScroll', wheel, false); | |
/** IE/Opera. */ | |
window.onmousewheel = document.onmousewheel = wheel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment