cup_of
cup_of

Reputation: 6687

Toggle class with delay on click

I have a button that when clicked on, I want it to toggle the class of another element with a delay. So the logic would be:

  1. click the button
  2. delay of 500ms
  3. add the class
  4. click the same button again
  5. delay of 500ms
  6. remove the class

Here is what i got so far:

jQuery(".menu-button").click(function(){
    jQuery(".nav-bar-logo").delay(500).queue(function() {
        jQuery(this).toggleClass("nav-bar-logo-active");
    });
});

I know there needs to be a queue when dealing with delays and addClass and removeClass but it doesn't seem to work with toggleClass

The code I got partially works: the class toggles after a delay on the initial click, but when clicking again it doesn't do anything.

Anyone have an idea to fix this?

Upvotes: 0

Views: 2069

Answers (2)

dippas
dippas

Reputation: 60553

As said in the comments you are looking for .setTimeout() instead. And as per your comment below, you want to toggle .nav-bar-logo, you can do like this:

jQuery('.menu-button').click(function() {
  window.setTimeout(function() {
    jQuery('.nav-bar-logo').toggleClass('nav-bar-logo-active');
  }, 500);
});

Here is a little DEMO

jQuery('.menu-button').click(function() {
  window.setTimeout(function() {
    jQuery('.nav-bar-logo').toggleClass('nav-bar-logo-active');
  }, 500);
});
.nav-bar-logo {
  padding: 50px;
  background: red
}

.nav-bar-logo-active {
  background: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="menu-button">
  toggle button
</button>
<div class="nav-bar-logo">
  I'm going to change color when button toggled
</div>

Upvotes: 1

sorak
sorak

Reputation: 2633

this is not available because it's in a delayed function, but we can access the click event:

jQuery(".menu-button").click(function(){
        window.setTimeout(function(){
                jQuery('.nav-bar-logo').toggleClass("nav-bar-logo-active");
            }, 500);
    });

Upvotes: 1

Related Questions