Skip to content

Instantly share code, notes, and snippets.

@theftprevention
Last active July 3, 2020 06:30
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save theftprevention/5959411 to your computer and use it in GitHub Desktop.
Save theftprevention/5959411 to your computer and use it in GitHub Desktop.
A small jQuery extension that disables the propagation of scroll events from the first element in the set of matched elements. Original function by Troy Alford of Stack Overflow.$("#object").scrollLock() enables the lock, and .scrollRelease() disables it.
$.fn.scrollLock=function(){return $(this).on("DOMMouseScroll mousewheel",function(h){var g=$(this),f=this.scrollTop,d=this.scrollHeight,b=g.height(),i=h.originalEvent.wheelDelta,a=i>0,c=function(){h.stopPropagation();h.preventDefault();h.returnValue=false;return false};if(!a&&-i>d-b-f){g.scrollTop(d);return c()}else{if(a&&i>f){g.scrollTop(0);return c()}}})};$.fn.scrollRelease=function(){return $(this).off("DOMMouseScroll mousewheel")};
@weir
Copy link

weir commented Oct 2, 2014

Thanks a ton for making this. FYI you're missing a period in the last statement. $fn instead of $.fn.

@jevanlingen
Copy link

If you don't want to prevent scrolling if element has no scrollbar, use this gist:

jQuery.fn.scrollLock=function(){return $(this).on("DOMMouseScroll mousewheel",function(h){var g=$(this),f=this.scrollTop,d=this.scrollHeight,b=g.height(),i=h.originalEvent.wheelDelta,a=i>0,c=function(){h.stopPropagation();h.preventDefault();h.returnValue=false;return false};if (g.get(0).scrollHeight > g.get(0).clientHeight) {if(!a&&-i>d-b-f){g.scrollTop(d);return c()}else{if(a&&i>f){g.scrollTop(0);return c()}}}})};$.fn.scrollRelease=function(){return $(this).off("DOMMouseScroll mousewheel")};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment