Delay adds class within 2 seconds when freezing ()

How to use attenuation or time delay on addClass(); ?

 $("#date_1").hover( function () { $(this).addClass("door"); $(this).addClass("doorstatic", "slow"); // after 2seconds i want to add this class during the hover }, function () { $(this).removeClass("door"); $(this).removeClass("doorstatic"); // both classes are instantly removed when hover off } ); 
+4
source share
3 answers
 $("#date_1").hover( function () { var $this = $(this); $this.addClass("door"); setTimeout(function() { $this.addClass("doorstatic"); }, 2000); // 2000 is in mil sec eq to 2 sec. }, function () { $(this).removeClass("door doorstatic"); } ); 

You can group your classes as removeClass("door doorstatic")

The problem is that if you hover over it and doorstatic for two seconds, you will still have the doorstatic class for your element.

Correction:

 $("#date_1").hover( function () { var $this = $(this), timer = $this.data("timer") || 0; clearTimeout(timer); $this.addClass("door"); timer = setTimeout(function() { $this.addClass("doorstatic"); }, 2000); // 2000 is in mil sec eq to 2 sec. $this.data("timer", timer); }, function () { var $this = $(this), timer = $this.data("timer") || 0; clearTimeout(timer); $this.removeClass("door doorstatic"); } ); 

Created a live example solution in jsFiddle .

+10
source

The javascript setTimeout can be used to run the code that you specify after the set delay in milliseconds.

Try the following:

 var timeout; $("#date_1").hover( function () { $(this).addClass("door"); timeout = setTimeout(function() { $(this).addClass("doorstatic"); }, 2000); }, function () { clearTimeout(timeout); $(this).removeClass("door doorstatic"); } ); 
+2
source

In fact, you can simply add the jQuery delay call to the addClass call.

Sort of

  $(this).addClass("door").delay(2000).addClass("doorstatic", "slow"); 

gotta do the trick.

+2
source

Source: https://habr.com/ru/post/1385515/


All Articles