Just disable scroll not hide it?
If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set
body { position: fixed; overflow-y:scroll }
you should still see the right scrollbar but the content is not scrollable. When you close the overlay just revert these properties with
body { position: static; overflow-y:auto }
I just proposed this way only because you wouldn't need to change any scroll event
Update
You could also do a slight improvement: if you get the document.documentElement.scrollTop
property via javascript just before the layer opening, you could dynamically assign that value as top
property of the body element: with this approach the page will stand in its place, no matter if you're on top or if you have already scrolled.
Css
.noscroll { position: fixed; overflow-y:scroll }
JS
$('body').css('top', -(document.documentElement.scrollTop) + 'px')
.addClass('noscroll');
Four little additions to the accepted solution:
- Apply 'noscroll' to html instead of to body to prevent double scroll bars in IE
- To check if there's actually a scroll bar before adding the 'noscroll' class. Otherwise, the site will also jump pushed by the new non-scrolling scroll bar.
- To keep any possible scrollTop so the entire page doesn't go back to the top (like Fabrizio's update, but you need to grab the value before adding the 'noscroll' class)
- Not all browsers handle scrollTop the same way as documented at http://help.dottoro.com/ljnvjiow.php
Complete solution that seems to work for most browsers:
CSS
html.noscroll {
position: fixed;
overflow-y: scroll;
width: 100%;
}
Disable scroll
if ($(document).height() > $(window).height()) {
var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
$('html').addClass('noscroll').css('top',-scrollTop);
}
Enable scroll
var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll');
$('html,body').scrollTop(-scrollTop);
Thanks to Fabrizio and Dejan for putting me on the right track and to Brodingo for the solution to the double scroll bar
With jQuery inluded:
disable
$.fn.disableScroll = function() {
window.oldScrollPos = $(window).scrollTop();
$(window).on('scroll.scrolldisabler',function ( event ) {
$(window).scrollTop( window.oldScrollPos );
event.preventDefault();
});
};
enable
$.fn.enableScroll = function() {
$(window).off('scroll.scrolldisabler');
};
usage
//disable
$("#selector").disableScroll();
//enable
$("#selector").enableScroll();