Reputation: 6251
I need to disable scrolling of the underlying content on my page while a modal is showing. I came across this code to disable page scrolling. (http://jsfiddle.net/77P2e/)
var $window = $(window), previousScrollTop = 0, scrollLock = false;
$window.scroll(function(event) {
if(scrollLock) {
$window.scrollTop(previousScrollTop);
}
previousScrollTop = $window.scrollTop();
});
$("#lock").click(function() {
scrollLock = !scrollLock;
});
It seems to work well and cover all possible scroll methods (wheel, middle mouse click, etc). But is there any disadvantage to using this as compared to setting overflow: hidden or some other method?
Upvotes: 0
Views: 106
Reputation: 4595
I would prefer to use the pointer-events in combination with overflow
. This would completely disable all interaction with a given DOM element and will partially limit interacting with its children.
.no-scroll {
overflow: hidden;
pointer-events: none;
}
If you only want to disable scrolling after the user has performed a certain action, or for any other reason, you can neatly apply this class to your code conditionally.
Because you use jQuery, you can use its addClass
and removeClass
functions to toggle this class on and off. You can also use toggleClass
, depending on preference. I personally prefer to not use it, because the addClass
and removeClass
makes me feel more in control.
Upvotes: 2
Reputation: 8389
It's not a bad way but you can also toggle overflow:hidden
like below
$("#lock").click(function() {
scrollLock = !scrollLock;
document.body.classList[scrollLock ? "add" : "remove"]("noScroll")
});
demo here.
Explanation:
I consider setting overflow: hidden
better way because of it's simplicity and in some browsers setting scroll positions manually could be jumpy. For example in Mac due to its scrolling effects.
Upvotes: 0