0

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>
Community
  • 1
  • 1
Black
  • 18,150
  • 39
  • 158
  • 271

4 Answers4

5

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

Tmb
  • 450
  • 12
  • 20
  • Thanks for your answer, it works but unfortunattely there is no fading. https://jsfiddle.net/dzzk8oxu/1/ – Black Feb 16 '16 at 14:05
  • @EdwardBlack The fading animation should be set in your css (see http://stackoverflow.com/questions/4411306/css3-transition-of-background-color for example) – Tmb Feb 16 '16 at 14:21
3

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>
Buzinas
  • 11,597
  • 2
  • 36
  • 58
2

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.

parik
  • 2,313
  • 12
  • 39
  • 67
Masood
  • 1,545
  • 1
  • 19
  • 30
-2

Use it like this:

$("div#test").click(function() {
    $(this).delay(2000).toggleClass('light').toggleClass('dark');
});
Atif Tariq
  • 2,650
  • 27
  • 34