Home > other >  How to remove a class with delay after a button is pressed?
How to remove a class with delay after a button is pressed?

Time:09-24

I have a full page navigation on my website. To make sure the page can't scroll when the navigation is opened, the body get's the 'no-scroll' class with overflow hidden. This also removes the scrollbar when the nav is opened.

When the nav button is pressed again and the nav closes, the class 'no-scroll' is removed from the body, revealing the scrollbar immediately. The navbar takes 1.05s to fully close. What I tried to achieve is to have the class 'no-scroll' not be removed immediately, but with a delay. Is there any way to do this?

This is the code I currently have to add and remove the class on button click:

<script>
  // when DOM is ready
    document.addEventListener('DOMContentLoaded', () => {
     // on .nav-menu-button click
     document.querySelectorAll('.nav-menu-button').forEach(trigger => {
      trigger.addEventListener('click', function(){ 
        this.x = ((this.x || 0)   1)%2; 
        if(this.x){ // 1st click
          document.querySelectorAll('body').forEach(target => target.classList.add('no-scroll'));
        }
        else{ // 2nd click (toggle)
          document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
        } 
      });
     });
    });
</script>

Thanks in advance!

CodePudding user response:

You can use setTimeout Function from WebAPI which helps in such cases. It registers approximate(minimum) timeout (in milliseconds, your case is 1050), after which specified function will be executed. In the end code will look like this:

setTimeout(() => {
  document.querySelectorAll('body').forEach(
    (target) => target.classList.remove('no-scroll')
  );
}, 1050);

CodePudding user response:

You could use setTimeout function. Here I've used 5 seconds delay:

setTimeout(function(){
 document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
},5000); 

CodePudding user response:

The code from Ann Francis solved it!

    <script>
// when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
 // on .nav-menu-button click
 document.querySelectorAll('.nav-menu-button').forEach(trigger => {
  trigger.addEventListener('click', function(){ 
    this.x = ((this.x || 0)   1)%2; 
    if(this.x){ // 1st click
      document.querySelectorAll('body').forEach(target => target.classList.add('no-scroll'));
    }
    else{ // 2nd click (toggle)
      setTimeout(function(){
                 document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
            },900); 
    } 
  });
 });
});
</script>

CodePudding user response:

You should try .add() and .remove() instead of classList.add() and classList.remove():

document.querySelectorAll('body').forEach(target => target.remove('no-scroll'));
  • Related