Black
Black

Reputation: 20262

toggleClass with delay

In this stackoverflow post the accepted answer claimed that it is possible to use toggleClass with a delay. But i did not find any information about a delay parameter on the official jquery API website.

I tried it but there is no delay after a click on the div.

$("div#test").click(function() {
    $(this).toggleClass('light', 2000).toggleClass('dark', 2000);
});
div {
  border: 1px dashed black;
}
.light {
  background-color: white;
}
.dark
{
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light" id="test">
    <p style="color:red">click here</p>
</div>

Upvotes: 0

Views: 19597

Answers (4)

Masood
Masood

Reputation: 1594

The .delay() method allows you to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue, only subsequent events in a queue are delayed. for example this will not delay the no-arguments forms of .toggleClass() or .show() or .hide() which do not use the effects queue.

Upvotes: 2

Tmb
Tmb

Reputation: 470

You can perform this operation with a basic timeout function :

$("div#test").click(function () {
    var el = $(this);
    window.setTimeout(function() {
        el.toggleClass('light').toggleClass('dark');
    }, 2000);
});

This is more efficient than a jQuery feature ;)

Upvotes: 6

Buzinas
Buzinas

Reputation: 11725

That's happening because the delay behavior is added by the jQuery UI library.

You're using only the jQuery library in your example.

jQuery website

jQuery UI website

Your example works if you include jQuery UI:

$("div#test").click(function() {
  $(this).toggleClass('light', 2000).toggleClass('dark', 2000);
});
div {
  border: 1px dashed black;
}

.light {
  background-color: white;
}

.dark {
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="light" id="test">
  <p style="color:red">click here</p>
</div>

Upvotes: 3

Atif Tariq
Atif Tariq

Reputation: 2772

Use it like this:

$("div#test").click(function() {
    $(this).delay(2000).toggleClass('light').toggleClass('dark');
});

Upvotes: -2

Related Questions