Yogesh Chauhan's Blog

How to disable scrolling on html body on menu click using JavaScript?

in JavaScript on June 27, 2021

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";
}


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What is a “promise” in JavaScript?JavaScriptHow to disable right click and drag and drop of images using jQuery?jQueryHow to change perception and behavior of a person for acceptance of new systems?MiscellaneousModules and its Core features in JavaScriptJavaScriptHow to center an image horizontally and vertically?CSSHow to add transparent text on top of an image using CSS?CSS