Sunday, December 30, 2012

Javascript Mouse Wheel Event Handler

I found several examples online but none of it works 100% as expected. I sort of modified them and came out with the version which works 100% for me on Chrome, IE, Safari and Firefox.

Here it is:


var ff = (navigator.userAgent.indexOf("Firefox") != -1);

if (ff) {
  mousewheelevent = "DOMMouseScroll";
}
else {
  mousewheelevent = "mousewheel";
}

if (document.attachEvent) {
  document.attachEvent("on"+mousewheelevent, catchWheel);
}
else if (document.addEventListener) {
  document.addEventListener(mousewheelevent, catchWheel, false);
}


function catchWheel(e){

  var evt=window.event || e;
  var delta=evt.detail? evt.detail : evt.wheelDelta/40;
  if (ff) { delta *= -1; } // Firefox gives opposite sign
  
  if (delta > 0) {
    // Scroll Up detected
    // Handle Scroll Up Event
  }
  else {
    // Scroll Down detected
    // Handle Scroll Down Event
  }
}




Enjoy!

No comments:

Post a Comment