Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .on("mouseenter") - wait 2 seconds then do action

Tags:

jquery

I have a script that shows hidden text when you hover over a div. But I want it to be delayed 2 seconds, and if the user moves the mouse away before 2 seconds I want nothing to be shown.

How do I do this?

What I have: http://jsfiddle.net/ZhrJT/

-

HTML:

<body>
    <div>hover this</div>
    <p class="hidden">unhidden!!</p>
</body>

JS:

$("body").on("mouseenter", "div", function(){
    $("p").removeClass("hidden");
}).on("mouseleave", "div", function(){
    $("p").addClass("hidden");
});

CSS:

div {
    background-color:red;
    height:100px;
}

p.hidden {
    display:none;  
}

p {
    background-color:yellow; 
    height:100px;   
}
like image 347
supercoolville Avatar asked Jan 26 '12 20:01

supercoolville


2 Answers

var timer;
$("body").on("mouseenter", "div", function(){
    timer = setTimeout(function () {
        $("p").removeClass("hidden");
    }, 2000);
}).on("mouseleave", "div", function(){
    clearTimeout(timer);
    $("p").addClass("hidden");
});

There ya go, it's that easy. Just set a timeout that will hide the element when it runs and cancel the timeout if the user mouseleaves the element.

like image 79
Jasper Avatar answered Nov 04 '22 22:11

Jasper


Use setTimeout/clearTimeout. Something like this:

$("body").on("mouseenter", "div", function(){
    $(this).data('timeout', setTimeout(function(){
       $("p").removeClass("hidden");
    }, 2000));
}).on("mouseleave", "div", function(){
    clearTimeout($(this).data('timeout'));
    $("p").addClass("hidden");
});
like image 7
Rocket Hazmat Avatar answered Nov 04 '22 22:11

Rocket Hazmat