Reputation: 6687
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:
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
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
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