Issue
I am creating a popup. When the user clicks a certain button, I want to show some error message. So when the popup appears, I want the background to stop scrolling. How do I do that? Here is the sample. when I click the 'menubtn', it will show the 'menu items'. And when the 'menu item' becomes active, the background should not be scrolled.
<div class="first">
<div class="menubtn">
menubtn
</div>
<div class="menu">
menu items
</div>
</div>
<div class="second">
second
</div>
Here in HTML, I created two div, and when I click a button, It opens a menu at the first div. The CSS code is like this.
.first,.second{
height:100vh;
font-size:50px;
display:grid;
place-content:center;
}
.menu{
position:absolute;
display:none;
}
.menu.active{
display:flex;
}
Then I added javascript to add and remove the menu whenever I click the button.
const menubtn = document.getElementsByClassName("menubtn")[0];
const menuopen = document.getElementsByClassName("menu")[0];
menubtn.addEventListener("click", () => {
menuopen.classList.toggle("active");
});
Now when the menubtn is active I want the div to stop scrolling.
edit: I think my question was unclear. The website is multiple pages and if I add body overflow hidden, then I can't scroll when I close the popup button. What I am trying to do is stop scrolling only when a popup is active, and again scroll when I close the popup.
Solution
I edit my answer I use an if condition to check if the active class exist the the overflow is hidden if not the overflow is auto
const menubtn = document.getElementsByClassName("menubtn")[0];
const menuopen = document.getElementsByClassName("menu")[0];
menubtn.addEventListener("click", () => {
menuopen.classList.toggle("active");
if (menuopen.classList.contains('active')) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = 'auto';
}
});
.first,
.second {
height: 100vh;
font-size: 50px;
display: grid;
place-content: center;
}
.menu {
display: none;
}
.menu.active {
display: flex;
}
<div class="first">
<div class="menubtn">
menubtn
</div>
<div class="menu">
menu items
</div>
</div>
<div class="second">
second
</div>
Answered By - Mohamad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.