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>

Answers:

Answer

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>

Answer

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

Answer

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.

Answer

Use it like this:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.