Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AddClass then removing a class

Tags:

In my Rails application, I send an Ajax request when the user hits the Save button, when it sends the request, I can return some jQuery.

What I'd like to do is add a class (saving), have a delay and then remove the class.

So, I added this:

$('.button').addClass('saving').delay(2000).removeClass('saving');

For some reason, it isn't working. What am I doing wrong?

like image 789
user1975031 Avatar asked Jan 21 '13 21:01

user1975031


People also ask

Can you remove a class with jQuery?

Similarly, you can remove the classes from the elements using the jQuery removeClass() method. The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.

How do you remove a class after some time?

setTimeout() method creates a function that will remove the blue class from the header element after 4000 milliseconds.

What does addClass do in jQuery?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.


2 Answers

.delay() is actually for animations.

Use setTimeout()

$('.button').addClass('saving');

setTimeout(function () { 
    $('.button').removeClass('saving');
}, 2000);
like image 101
Mark Pieszak - Trilon.io Avatar answered Oct 02 '22 16:10

Mark Pieszak - Trilon.io


delay only works with animation-related methods, you can use queue method:

$('.button').addClass('saving').delay(2000).queue(function( next ){
    $(this).removeClass('saving'); 
    next();
});

http://jsfiddle.net/Rp6Xw/44/

like image 23
undefined Avatar answered Oct 02 '22 16:10

undefined