Calling a function when toggleClass has been completed.

Today I came across a requirement where I had to call a function on completion of toggleClass function.

So let’s find out how to do it, considering that we have a similar requirement.

we need to add a class on click of some div  and at the same time we need to apply some attribute to that div (we will consider style attribute here).and when class is  toggled then attribute should be toggled too.

As we know how the toggleClass works, If the element has the specific class then it removes it and adds the class if the element doesn’t have the class.

So what we need to do is,when element doesn’t have a  class we need to add that specific class, and if its having that specific class we need to add style attribute only and remove that class.

<div id=’toggleMe’ class=’container in’ />  (if its not having ‘in’ class then add the class)

on toggle it wll look like below link

<div id=”toggleMe” class=’container’ style=’margin-left:20px’/> (if the link is already having this class then remove the class and add style attribute).

$('div').click(function() {
$('#loader').toggleClass('newclass', 1000).promise().done(function(){
if(!$(this).hasClass('newclass'))
{
$(this).css('margin-left','100px');
}
else{
$(this).removeAttr('style');
}
});
});

Please go through the js fiddle demo here.

I hope it helps. 🙂

Leave a comment