I\'m using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason
This is the simplest solution I got so far. And believe me I tried all the others and this is the easiest one. It works great on Windows devices, which pushes the page from the right to have room for the system scrollbar and IOS devices which don't require space for their scrollbars in the browsers. So by using this you wont need to add padding on the right so the page doesn't flicker when you hide the overflow of the body or html with css.
The solution is pretty simple if you think about it. The idea is to give the window.scrollTop() the same exact position at the moment that a popup is opened. Also change that position when the window resizes ( as the scroll position changes once that happens ).
So here we go...
First lets create the variable that will let you know that the popup is open and call it stopWindowScroll. If we don't do this then you'll get an error of an undefined variable on your page and set it to 0 - as not active.
$(document).ready(function(){
stopWindowScroll = 0;
});
Now lets make the open popup function witch can be any function in your code that triggers whatever popup you are using as a plugin or custom. In this case it will be a simple custom popup with a simple document on click function.
$(document).on('click','.open-popup', function(){
// Saving the scroll position once opening the popup.
stopWindowScrollPosition = $(window).scrollTop();
// Setting the stopWindowScroll to 1 to know the popup is open.
stopWindowScroll = 1;
// Displaying your popup.
$('.your-popup').fadeIn(300);
});
So the next thing we do is create the close popup function, which I repeat again can be any function you already have created or are using in a plugin. The important thing is that we need those 2 functions to set the stopWindowScroll variable to 1 or 0 to know when it's open or closed.
$(document).on('click','.open-popup', function(){
// Setting the stopWindowScroll to 0 to know the popup is closed.
stopWindowScroll = 0;
// Hiding your popup
$('.your-popup').fadeOut(300);
});
Then lets create the window.scroll function so we can prevent the scrolling once the stopWindowScroll mentioned above is set to 1 - as active.
$(window).scroll(function(){
if(stopWindowScroll == 1) {
// Giving the window scrollTop() function the position on which
// the popup was opened, this way it will stay in its place.
$(window).scrollTop(stopWindowScrollPosition);
}
});
Thats it. No CSS required for this to work except your own styles for the page. This worked like a charm for me and I hope it helps you and others.
Here is a working example on JSFiddle:
JS Fiddle Example
Let me know if this helped. Regards.