jQuery disable scroll when mouse over an absolute div

This has been a popular question so I am updating to give an overview of the answers provided here and which may be best for you. There are three unique solutions included. Two are from Amos and one is from myself. However, each operates differently.

  1. Amos – Set overflow:hidden on body. This is simple and works great. But the main window’s scrollbars will flash in and out.
  2. Amos – Use javascript to disable mouse wheel. This is great if you don’t need mousewheel at all.
  3. This answer – Use javascript to scroll only the element you are over. This is the best answer if your inner div needs to scroll, but you don’t want any other divs to scroll. The example fiddle showcases this.

http://jsfiddle.net/eXQf3/371/

The code works as follows:

  • Catch scroll event on the current element
  • Cancel the scroll event
  • Manually scroll the current element only

 

$('#abs').bind('mousewheel DOMMouseScroll', function(e) {
    var scrollTo = null;

    if (e.type == 'mousewheel') {
        scrollTo = (e.originalEvent.wheelDelta * -1);
    }
    else if (e.type == 'DOMMouseScroll') {
        scrollTo = 40 * e.originalEvent.detail;
    }

    if (scrollTo) {
        e.preventDefault();
        $(this).scrollTop(scrollTo + $(this).scrollTop());
    }
});​

Changelog:

  • FF support
  • scrollTo null check to revert to default behavior in case something unforeseen happens
  • support for jQuery 1.7.

Leave a Comment

tech