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 add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Data Flows in ReactReactfor @each loop in SCSSSCSSHow to add a ribbon on top of a container using CSS?CSSPostgreSQL BETWEENPostgresAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to update or disable WordPress Post Revisions?WordPress