Search code examples
jquerycssoverflowtoggledocument-body

Not able to scroll through body after closing toggle


I prevented the user to scroll through the HTML body once they open the toggle using jQuery. However, I am struggling in enabling the scrolling back once the toggle is closed. I think I should use two jQuery classes in

$('body').css({overflow: 'hidden'});

with the other one stating that .toggleClass is not active anymore. However, I don't know how to do this yet or if it is possible.

Thanks in advance for helping this newbie.

Here's the link to my CodePen in case you find it easier. The same code is attached below without the lipsum text.

CodePen: https://codepen.io/fergos2/pen/jOOWeqR

$(document).ready(function() {
  $('.toggle').click(function() {
    $('.toggle').toggleClass('active');
    $('.toggle-content').toggleClass('active');
    $('body').css({overflow: 'hidden'});
  });
});
body {
  overflow: auto;
}

.container {
  width: 100%;
  height: 1000px;
  margin: 0 auto;
  background-color: #eee;
}

.text {
  padding: 10px;
}

.wrapper {
  background-color: pink;
  position: relative;

  display: flex;
  align-items: center;
}

.toggle {
  display: block;
  width: 20px;
  height: 20px;
  float: left;
  cursor: pointer;
  color: white;
  text-align: center;
  background-color: green;
  margin: 10px;
}

.toggle.active {
  background-color: red;
}

.toggle-content {
  display: none;
}

.toggle-content.active{
  display: block;
  background-color: white;
  border: 1px solid black;
  position: absolute;
  top: 40px;
  left: 0;
}
<div class="container">
  <div class="wrapper">
    <div class="toggle">T</div>
    <div class="toggle-content">
      <p>Some content</p>
    </div>
  </div>

  <div class="text">
  </div>

</div>

Solution

  • You can also use :

    $("body").toggleClass("hidden");
    

    And then create a class in your css:

    .hidden {
      overflow: hidden;
    }