Using jQuery, I would like to disable scrolling of the body:
My idea is to:
body{ overflow: hidden;}
For folks who have centered layouts (via margin:0 auto;
), here's a mash-up of the position:fixed
solution along with @tfe's proposed solution.
Use this solution if you're experiencing page-snapping (due to the scrollbar showing/hiding).
// lock scroll position, but retain settings for later
var scrollPosition = [
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
];
var $html = $('html'); // bow to the demon known as MSIE(v7)
$html.addClass('modal-noscroll');
$html.data('scroll-position', scrollPosition);
$html.data('margin-top', $html.css('margin-top'));
$html.css('margin-top', -1 * scrollPosition[1]);
…combined with…
// un-lock scroll position
var $html = $('html').removeClass('modal-noscroll');
var scrollPosition = $html.data('scroll-position');
var marginTop = $html.data('margin-top');
$html.css('margin-top', marginTop);
window.scrollTo(scrollPosition[0], scrollPosition[1])
…and finally, the CSS for .modal-noscroll
…
.modal-noscroll
{
position: fixed;
overflow-y: scroll;
width: 100%;
}
I would venture to say this is more of a proper fix than any of the other solutions out there, but I haven't tested it that thoroughly yet… :P
Edit: please note that I have no clue how badly this might perform (read: blow up) on a touch device.
I put an answer that might help here: jQuery simplemodal disable scrolling
It shows how to turn off the scroll bars without shifting the text around. You can ignore the parts about simplemodal.
This will completely disable scrolling:
$('html, body').css({
overflow: 'hidden',
height: '100%'
});
To restore:
$('html, body').css({
overflow: 'auto',
height: 'auto'
});
Tested it on Firefox and Chrome.
you can use this code:
$("body").css("overflow", "hidden");
You can attach a function to scroll events and prevent its default behaviour.
var $window = $(window);
$window.on("mousewheel DOMMouseScroll", onMouseWheel);
function onMouseWheel(e) {
e.preventDefault();
}
https://jsfiddle.net/22cLw9em/
Somebody posted this code, which has the problem of not retaining the scroll position when restored. The reason is that people tend to apply it to html and body or just the body but it should be applied to html only. This way when restored the scroll position will be kept:
$('html').css({
'overflow': 'hidden',
'height': '100%'
});
To restore:
$('html').css({
'overflow': 'auto',
'height': 'auto'
});