When do you need to disable scrolling?
In most cases where you have overlay menu and the menu is on top of the page content, you’d want to stop scrolling of the content inside the body.
Note that, you need to keep the scrolling of the menu enabled if the menu content is overflowing the window viewport.
How to disable the scrolling?
We can use CSS overflow property to stop scrolling based on click using JavaScript.
Examples
Add these functions in your JavaScript file and call them on a button click or any other events.
let b = document.body;
function bodyOverflowHidden() {
b.style.overflow = "hidden";
}
function bodyOverflowAuto() {
b.style.overflow = "auto";
}
You could also control overflow-x and overflow-y separately.
function bodyOverflowHidden() {
b.style.overflowY = "hidden";
b.style.overflowX = "hidden";
}
function bodyOverflowAuto() {
b.style.overflowY = "auto";
b.style.overflowX = "hidden";
}
How to disable scroll of an html element?
If you want, you could also disable scroll on the html document itself.
function bodyOverflowHidden() {
document.getElementsByTagName("html")[0].style.overflow = "hidden";
}
function bodyOverflowAuto() {
document.getElementsByTagName("html")[0].style.overflow = "auto";
}
body disable html overflow solution