Mouse wheel event


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*
  2.  * Author URL: http://adomas.org/javascript-mouse-wheel/
  3.  */
  4.  
  5. /** This is high-level function.
  6.  * It must react to delta being more/less than zero.
  7.  */
  8. function handle(delta) {
  9. if (delta < 0)
  10. …;
  11. else
  12. …;
  13. }
  14.  
  15. /** Event handler for mouse wheel event.
  16.  */
  17. function wheel(event){
  18. var delta = 0;
  19. if (!event) /* For IE. */
  20. event = window.event;
  21. if (event.wheelDelta) { /* IE/Opera. */
  22. delta = event.wheelDelta/120;
  23. /** In Opera 9, delta differs in sign as compared to IE.
  24.   */
  25. if (window.opera)
  26. delta = -delta;
  27. } else if (event.detail) { /** Mozilla case. */
  28. /** In Mozilla, sign of delta is different than in IE.
  29.   * Also, delta is multiple of 3.
  30.   */
  31. delta = -event.detail/3;
  32. }
  33. /** If delta is nonzero, handle it.
  34.   * Basically, delta is now positive if wheel was scrolled up,
  35.   * and negative, if wheel was scrolled down.
  36.   */
  37. if (delta)
  38. handle(delta);
  39. }
  40.  
  41. /** Initialization code.
  42.  * If you use your own event management code, change it as required.
  43.  */
  44. if (window.addEventListener)
  45. /** DOMMouseScroll is for mozilla. */
  46. window.addEventListener('DOMMouseScroll', wheel, false);
  47. /** IE/Opera. */
  48. window.onmousewheel = document.onmousewheel = wheel;

URL: http://adomas.org/javascript-mouse-wheel/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.