How to prevent Body from scrolling when a modal is opened using jQuery ?
Last Updated :
05 Aug, 2024
In this article, we will learn how we can prevent the body from scrolling when a popup or modal is opened using jQuery. This task can be easily accomplished by setting the value of the overflow property to hidden using the css() method or by adding and removing the class from the body.
Using the css() method to set the overflow property
The css() method can be used to prevent the scroll of the body when a modal is opened by passing the overflow property and its value as hidden to this method as parameters in the form of string.
Syntax:
$('element_selector').css('overflow', 'hidden');
Example: The below example explains how you can set overflow hidden to the body when the modal gets open.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
</script>
<style>
body {
padding: 5% 20%;
}
#container {
z-index: 1;
}
#btn {
border: none;
font-size: 24px;
padding: 12px 36px;
color: white;
background-color: green;
cursor: pointer;
}
#modal {
height: 200px;
width: 400px;
padding: 60px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
background-color: green;
color: white;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<!--Button to toggle $("#modal")-->
<button id="btn">
Toggle modal
</button>
<!--$("#modal") container-->
<div id="modal" class="hidden">
<div id="modal-body">
<h1>GeeksforGeeks</h1>
<h2>This is a modal</h2>
</div>
</div>
<!--Long text so that the body scrolls-->
<div id="container">
<h1>
Given a graph and a source vertex in
the graph, find shortest paths from
source to all vertices in the given
graph. Dijkstra’s algorithm is very
similar to Prim’s algorithm for minimum
spanning tree. Like Prim’s MST, we
generate a SPT (shortest path tree)
with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet
included in shortest path tree. At every
step of the algorithm, we find a vertex
which is in the other set (set of not yet
included) and has a minimum distance from
the source. Below are the detailed steps
used in Dijkstra’s algorithm to find the
shortest path from a single source vertex
to all other vertices in the given graph.
Algorithm Create a set sptSet (shortest
path tree set) that keeps track of vertices
included in shortest path tree, i.e., whose
minimum distance from source is calculated
and finalized. Initially, this set is empty.
Assign a distance value to all vertices in
the input graph. Initialize all distance
values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While
sptSet doesn’t include all vertices Pick a
vertex u which is not there in sptSet and
has minimum distance value. Include u to
sptSet. Update distance value of all adjacent
vertices of u. To update the distance values,
iterate through all adjacent vertices. For
every adjacent vertex v, if sum of distance
value of u (from source) and weight of edge
u-v, is less than the distance value of v,
then update the distance value of v.
Given a graph and a source vertex in the
graph, find shortest paths from source to
all vertices in the given graph. Dijkstra’s
algorithm is very similar to Prim’s
algorithm for minimum spanning tree.
Like Prim’s MST, we generate a SPT (shortest
path tree) with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet included
in shortest path tree.
At every step of the algorithm, we find a
vertex which is in the other set (set of not
yet included) and has a minimum distance
from the source.
Below are the detailed steps used in
Dijkstra’s algorithm to find the shortest
path from a single source vertex to all other
vertices in the given graph. Algorithm
Create a set sptSet (shortest path tree set)
that keeps track of vertices included in
shortest path tree, i.e., whose minimum
distance from source is calculated and
finalized. Initially, this set is empty. Assign
a distance value to all vertices in the input
graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While sptSet
doesn’t include all vertices Pick a vertex u
which is not there in sptSet and has minimum
distance value. Include u to sptSet.
Update distance value of all adjacent vertices
of u. To update the distance values, iterate
through all adjacent vertices. For every
adjacent vertex v, if sum of distance value
of u (from source) and weight of edge u-v,
is less than the distance value of v, then
update the distance value of v.
</h1>
</div>
<script>
$(document).ready(()=>{
$("#btn").click(function () {
$("#modal").toggleClass("hidden");
if ($("#modal").hasClass("hidden")) {
// Enable scroll
$("body").css('overflow', "auto");
} else {
// Disable scroll
$("body").css('overflow', "hidden");
}
});
});
</script>
</body>
</html>
Output:
By toggling the class using toggleClass() method
In this approach, we will try to prevent the body scroll using the toggleClass() method. Here, we will define a class with a property overflow: hidden and then toggle that class to the body element to enable and disable the scroll with respect to the modal.
Syntax:
$('element_selector').toggleClass('className');
Example: The below example illustrate the use of the toggleClass() method to prevent the body scroll.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
</script>
<style>
body {
padding: 5% 20%;
}
#container {
z-index: 1;
}
#btn {
border: none;
font-size: 24px;
padding: 12px 36px;
color: white;
background-color: green;
cursor: pointer;
}
#modal {
height: 200px;
width: 400px;
padding: 60px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
background-color: green;
color: white;
}
.hidden {
display: none;
}
.stopScroll{
overflow: hidden;
}
</style>
</head>
<body>
<!--Button to toggle $("#modal")-->
<button id="btn">
Toggle modal
</button>
<!--$("#modal") container-->
<div id="modal" class="hidden">
<div id="modal-body">
<h1>GeeksforGeeks</h1>
<h2>This is a modal</h2>
</div>
</div>
<!--Long text so that the body scrolls-->
<div id="container">
<h1>
Given a graph and a source vertex in
the graph, find shortest paths from
source to all vertices in the given
graph. Dijkstra’s algorithm is very
similar to Prim’s algorithm for minimum
spanning tree. Like Prim’s MST, we
generate a SPT (shortest path tree)
with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet
included in shortest path tree. At every
step of the algorithm, we find a vertex
which is in the other set (set of not yet
included) and has a minimum distance from
the source. Below are the detailed steps
used in Dijkstra’s algorithm to find the
shortest path from a single source vertex
to all other vertices in the given graph.
Algorithm Create a set sptSet (shortest
path tree set) that keeps track of vertices
included in shortest path tree, i.e., whose
minimum distance from source is calculated
and finalized. Initially, this set is empty.
Assign a distance value to all vertices in
the input graph. Initialize all distance
values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While
sptSet doesn’t include all vertices Pick a
vertex u which is not there in sptSet and
has minimum distance value. Include u to
sptSet. Update distance value of all adjacent
vertices of u. To update the distance values,
iterate through all adjacent vertices. For
every adjacent vertex v, if sum of distance
value of u (from source) and weight of edge
u-v, is less than the distance value of v,
then update the distance value of v.
Given a graph and a source vertex in the
graph, find shortest paths from source to
all vertices in the given graph. Dijkstra’s
algorithm is very similar to Prim’s
algorithm for minimum spanning tree.
Like Prim’s MST, we generate a SPT (shortest
path tree) with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet included
in shortest path tree.
At every step of the algorithm, we find a
vertex which is in the other set (set of not
yet included) and has a minimum distance
from the source.
Below are the detailed steps used in
Dijkstra’s algorithm to find the shortest
path from a single source vertex to all other
vertices in the given graph. Algorithm
Create a set sptSet (shortest path tree set)
that keeps track of vertices included in
shortest path tree, i.e., whose minimum
distance from source is calculated and
finalized. Initially, this set is empty. Assign
a distance value to all vertices in the input
graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While sptSet
doesn’t include all vertices Pick a vertex u
which is not there in sptSet and has minimum
distance value. Include u to sptSet.
Update distance value of all adjacent vertices
of u. To update the distance values, iterate
through all adjacent vertices. For every
adjacent vertex v, if sum of distance value
of u (from source) and weight of edge u-v,
is less than the distance value of v, then
update the distance value of v.
</h1>
</div>
<script>
$(document).ready(()=>{
$("#btn").click(function () {
$("#modal").toggleClass("hidden");
$('body').toggleClass('stopScroll');
});
});
</script>
</body>
</html>
Output:
Using the addClass() and removeClass() methods
The addClass() and removeClass() method can be used to add the class which takes the overflow: hidden property when the modal is opened and remove it when the modal is closed by simply passing the class as parameter to these methods in the form of string.
Syntax:
$('element_selector').addClass('className')/removeClass('className')
Example: The below example implements the addClass() and the removeClass() methods to prevent the scroll.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
</script>
<style>
body {
padding: 5% 20%;
}
#container {
z-index: 1;
}
#btn {
border: none;
font-size: 24px;
padding: 12px 36px;
color: white;
background-color: green;
cursor: pointer;
}
#modal {
height: 200px;
width: 400px;
padding: 60px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
background-color: green;
color: white;
}
.hidden {
display: none;
}
.stopScroll{
overflow: hidden;
}
</style>
</head>
<body>
<!--Button to toggle $("#modal")-->
<button id="btn">
Toggle modal
</button>
<!--$("#modal") container-->
<div id="modal" class="hidden">
<div id="modal-body">
<h1>GeeksforGeeks</h1>
<h2>This is a modal</h2>
</div>
</div>
<!--Long text so that the body scrolls-->
<div id="container">
<h1>
Given a graph and a source vertex in
the graph, find shortest paths from
source to all vertices in the given
graph. Dijkstra’s algorithm is very
similar to Prim’s algorithm for minimum
spanning tree. Like Prim’s MST, we
generate a SPT (shortest path tree)
with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet
included in shortest path tree. At every
step of the algorithm, we find a vertex
which is in the other set (set of not yet
included) and has a minimum distance from
the source. Below are the detailed steps
used in Dijkstra’s algorithm to find the
shortest path from a single source vertex
to all other vertices in the given graph.
Algorithm Create a set sptSet (shortest
path tree set) that keeps track of vertices
included in shortest path tree, i.e., whose
minimum distance from source is calculated
and finalized. Initially, this set is empty.
Assign a distance value to all vertices in
the input graph. Initialize all distance
values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While
sptSet doesn’t include all vertices Pick a
vertex u which is not there in sptSet and
has minimum distance value. Include u to
sptSet. Update distance value of all adjacent
vertices of u. To update the distance values,
iterate through all adjacent vertices. For
every adjacent vertex v, if sum of distance
value of u (from source) and weight of edge
u-v, is less than the distance value of v,
then update the distance value of v.
Given a graph and a source vertex in the
graph, find shortest paths from source to
all vertices in the given graph. Dijkstra’s
algorithm is very similar to Prim’s
algorithm for minimum spanning tree.
Like Prim’s MST, we generate a SPT (shortest
path tree) with given source as root.
We maintain two sets, one set contains
vertices included in shortest path tree,
other set includes vertices not yet included
in shortest path tree.
At every step of the algorithm, we find a
vertex which is in the other set (set of not
yet included) and has a minimum distance
from the source.
Below are the detailed steps used in
Dijkstra’s algorithm to find the shortest
path from a single source vertex to all other
vertices in the given graph. Algorithm
Create a set sptSet (shortest path tree set)
that keeps track of vertices included in
shortest path tree, i.e., whose minimum
distance from source is calculated and
finalized. Initially, this set is empty. Assign
a distance value to all vertices in the input
graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source
vertex so that it is picked first. While sptSet
doesn’t include all vertices Pick a vertex u
which is not there in sptSet and has minimum
distance value. Include u to sptSet.
Update distance value of all adjacent vertices
of u. To update the distance values, iterate
through all adjacent vertices. For every
adjacent vertex v, if sum of distance value
of u (from source) and weight of edge u-v,
is less than the distance value of v, then
update the distance value of v.
</h1>
</div>
<script>
$(document).ready(()=>{
$("#btn").click(function () {
$("#modal").toggleClass("hidden");
if ($("#modal").hasClass("hidden")) {
// Enable scroll
$("body").removeClass('stopScroll');
} else {
// Disable scroll
$("body").addClass('stopScroll');
}
});
});
</script>
</body>
</html>
Output:
Similar Reads
jQuery Tutorial jQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Getting Started with jQuery jQuery is a fast lightweight, and feature-rich JavaScript library that simplifies many common tasks in web development. It was created by John Resign and first released in 2006. It makes it easier to manipulate HTML documents, handle events, create animations, and interact with DOM(Document Object M
4 min read
jQuery Introduction jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM). jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser Java
7 min read
jQuery Syntax The jQuery syntax is essential for leveraging its full potential in your web projects. It is used to select elements in HTML and perform actions on those elements.jQuery Syntax$(selector).action()Where - $ - It the the shorthand for jQuery function.(selector) - It defines the HTML element that you w
2 min read
jQuery CDN A Content Delivery Network (CDN) is a system of distributed servers that deliver web content to users based on their geographic location. Including the jQuery CDN in your project can improve the performance, enhance reliability, and simplify maintenance.What is a jQuery CDN?A jQuery CDN is a service
4 min read
jQuery Selectors
JQuery SelectorsWhat is a jQuery Selector?jQuery selectors are functions that allow you to target and select HTML elements in the DOM based on element names, IDs, classes, attributes, and more, facilitating manipulation and interaction. Syntax: $(" ")Note: jQuery selector starts with the dollar sign $, and you encl
5 min read
jQuery * SelectorThe jQuery * selector selects all the elements in the document, including HTML, body, and head. If the * selector is used together with another element then it selects all child elements within the element used. Syntax: $("*")Parameters: *: This parameter is used to select all elements.Example 1: Se
1 min read
jQuery #id SelectorjQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating on the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Aja
1 min read
jQuery .class SelectorThe jQuery .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements. Syntax: $(".class") Parameter: class: This parameter is required to specify the class of the elements to be selected.Example 1: In this example,
1 min read
jQuery Events
jQuery Effects
jQuery HTML/CSS
jQuery Traversing