Cross Browser Wheel Event Listener


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

A nifty event listener for handling wheel events. Listens for the DOM3 Wheel Event first, then falls back to MouseWheel, and finally DOMMouseScroll.


Copy this code and paste it in your HTML
  1. // creates a global "addWheelListener" method
  2. // example: addWheelListener( elem, callback );
  3.  
  4. (function(window,document) {
  5.  
  6. var prefix = "", _addEventListener, onwheel, support;
  7.  
  8. // detect event model
  9. if ( window.addEventListener ) {
  10. _addEventListener = "addEventListener";
  11. } else {
  12. _addEventListener = "attachEvent";
  13. prefix = "on";
  14. }
  15.  
  16. // detect available wheel event
  17. if ( document.onmousewheel !== undefined ) {
  18. // Webkit and IE support at least "mousewheel"
  19. support = "mousewheel"
  20. }
  21. try {
  22. // Modern browsers support "wheel"
  23. WheelEvent("wheel");
  24. support = "wheel";
  25. } catch (e) {}
  26. if ( !support ) {
  27. // let's assume that remaining browsers are older Firefox
  28. support = "DOMMouseScroll";
  29. }
  30. window.addWheelListener = function( elem, callback, useCapture ) {
  31. _addWheelListener( elem, support, callback, useCapture );
  32.  
  33. // handle MozMousePixelScroll in older Firefox
  34. if( support == "DOMMouseScroll" ) {
  35. _addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
  36. }
  37. };
  38.  
  39. function _addWheelListener( elem, eventName, callback, useCapture ) {
  40. elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
  41. !originalEvent && ( originalEvent = window.event );
  42.  
  43. // create a normalized event object
  44. var event = {
  45. // keep a ref to the original event object
  46. originalEvent: originalEvent,
  47. target: originalEvent.target || originalEvent.srcElement,
  48. type: "wheel",
  49. deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
  50. deltaX: 0,
  51. delatZ: 0,
  52. preventDefault: function() {
  53. originalEvent.preventDefault ?
  54. originalEvent.preventDefault() :
  55. originalEvent.returnValue = false;
  56. }
  57. };
  58.  
  59. // calculate deltaY (and deltaX) according to the event
  60. if ( support == "mousewheel" ) {
  61. event.deltaY = - 1/40 * originalEvent.wheelDelta;
  62. // Webkit also support wheelDeltaX
  63. originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
  64. } else {
  65. event.deltaY = originalEvent.detail;
  66. }
  67.  
  68. // it's time to fire the callback
  69. return callback( event );
  70.  
  71. }, useCapture || false );
  72. }
  73.  
  74. })(window,document);

URL: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference/wheel?redirect=no

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.