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;
}
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 mouseleave
s the element.
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With