Posted By

smagic on 10/02/15


Tagged

javascript mousewheelevents


Versions (?)

Javascript Disable Enabling Mouse Wheel


 / Published in: JavaScript
 

I occasionally need to block mouse wheel scrolling when I’m working with JavaScript. Of course, this is only momentary, such as when I need to display an overlay of some sort.

I usually use MooTools for my scripting needs, but frameworks can sometimes become a handicap. While it makes coding easy, it makes you dependent on it and then you forget the basics.

In this article, I will show you how to disable the mouse wheel by adding mousewheel events and how to remove them when you are done. Each line of code has comments to show which browsers need it.

Solid Tip: This script will not require a JavaScript framework and has been tested in Firefox, Chrome, Safari, IE7, and IE8.

}

Notice my use of document in the instead of window when adding and removing the event. The IE versions would fail using window, but it does need window.event. Obviously, we would never expect IE to do it the easy way…

  1. //Blocking the Mouse Wheel
  2. document.onmousewheel = function(){ stopWheel(); } /* IE7, IE8 */
  3. if(document.addEventListener){ /* Chrome, Safari, Firefox */
  4. document.addEventListener('DOMMouseScroll', stopWheel, false);
  5. }
  6.  
  7. function stopWheel(e){
  8. if(!e){ e = window.event; } /* IE7, IE8, Chrome, Safari */
  9. if(e.preventDefault) { e.preventDefault(); } /* Chrome, Safari, Firefox */
  10. e.returnValue = false; /* IE7, IE8 */
  11. }
  12. //Re-enabling the Wheel
  13. document.onmousewheel = null; /* IE7, IE8 */
  14. if(document.addEventListener){ /* Chrome, Safari, Firefox */
  15. document.removeEventListener('DOMMouseScroll', stopWheel, false);
  16. }

Report this snippet  

You need to login to post a comment.