Home > Software design >  How do I stop scrolling when I open a menu in one div?
How do I stop scrolling when I open a menu in one div?

Time:07-27

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 >
    <div >
        menubtn
    </div>
    <div >
        menu items
    </div>
</div>
<div >
    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.

CodePudding user response:

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 >
  <div >
    menubtn
  </div>
  <div >
    menu items
  </div>
</div>
<div >
  second
</div>

CodePudding user response:

//in javascript

`

menubtn.addEventListener("click", () => {

  menuopen.classList.toggle("active");
  document.querySelector("body").style.overflowY="hidden"
});

`

// if is dom

// in css

.menubtn{ position:absolute }

CodePudding user response:

CSS: body { overflow: hidden; }

  • Related