Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
How to remove a class with delay after a button is pressed?

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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); 
about 4 years ago · Juan Pablo Isaza Report

0

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

document.querySelectorAll('body').forEach(target => target.remove('no-scroll'));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!