astropanic
astropanic

Reputation: 10939

jQuery add class for certain time

How I can add a css class to an element for only 10 seconds ?

Upvotes: 6

Views: 16242

Answers (4)

hhs
hhs

Reputation: 714

You can add class , and remove it without setTimeout() like this.

$(".count-box", element).addClass("red");
$(".count-box", element).removeClass("red", 10000);

Upvotes: -1

Dan S
Dan S

Reputation: 845

A nicely reusable way would be this little jQuery plugin:

(function($){

    $.fn.extend({ 

        addTemporaryClass: function(className, duration) {
            var elements = this;
            setTimeout(function() {
                elements.removeClass(className);
            }, duration);

            return this.each(function() {
                $(this).addClass(className);
            });
        }
    });

})(jQuery);

Use like so:

$("#myElement").addTemporaryClass("myClass", 10000);

Upvotes: 27

Nalum
Nalum

Reputation: 4213

Use setTimeout(function,10000); directly after you set the class on the element to remove the class from that element.

Upvotes: 0

SLaks
SLaks

Reputation: 887315

You can add the class, then call setTimeout(function() { ... }, 10000) to remove it 10,000 milliseconds later.

Upvotes: 3

Related Questions