Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggleClass callback how to?

I have this simple jQuery event with toggleClass:

$(this).on("click", function() {
    $(this).toggleClass("fa-stop-circle");
});

I would like to call some method if fa-stop-circle is added. How can I monitor this event?

like image 1000
deroccha Avatar asked Oct 19 '25 12:10

deroccha


2 Answers

toggleClass() doesn't have a callback, however you can check if the element has the class immediately after calling toggleClass(), like this:

$(this).on("click", function() {
    var $el = $(this).toggleClass("fa-stop-circle");
    if ($el.hasClass('fa-stop-circle')) {
        // do something...
    }
});

Working example

like image 141
Rory McCrossan Avatar answered Oct 21 '25 04:10

Rory McCrossan


You should use .done() in combination with .promise().

The promise will return deferred object;

Then done adds handler when deferred object is resolved.

$(this).toggleClass("fa-stop-circle").promise().done(function() {
    if ($this).hasClass("fa-stop-circle")) {
        // your code
    }
});
like image 43
Martin Hučko Avatar answered Oct 21 '25 03:10

Martin Hučko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!