Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay adding a class for 2 seconds in hover()

Tags:

jquery

How do I use easing 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
    }
);
like image 714
TheBlackBenzKid Avatar asked Dec 03 '22 00:12

TheBlackBenzKid


1 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 like removeClass("door doorstatic")

The problem here is that if you mouseover and before two seconds mouse out you will still have the class doorstatic on you element.

The fix:

$("#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 of the solution at jsFiddle.

like image 77
Andreas Louv Avatar answered Dec 26 '22 12:12

Andreas Louv