I have a div and I want to fire an event only after user continuous hovers his mouse for 3 sec. My code doesn't work well because it fires right after hover and doesn't "wait".
Code:
$(".inner_pic").mouseenter(function () {
setTimeout(function () {
alert('testing');
}, 3000);
}).mouseleave(function () {
alert('finish');
});
答案 0 :(得分:25)
You need to store timeout id somewhere and clear it on mouseout. It's convenient to use data property to save this id:
$(".inner_pic").mouseenter(function () {
$(this).data('timeout', setTimeout(function () {
alert('testing');
}, 3000));
}).mouseleave(function () {
clearTimeout($(this).data('timeout'));
alert('finish');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner_pic">PICTURE</div>
答案 1 :(得分:11)
You can achieve this by delay
option:
$('#elem').popover({
trigger: "hover",
delay: {show : 3000, hide : 0} });
答案 2 :(得分:2)
Checkout the below code
var myVar;
$( "div#container" )
.mouseover(function() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
})
.mouseout(function() {
clearTimeout(myVar);
});
div {
background: red;
margin: 20px;
height: 100px;
width: 100px;
display:block;
cursor: pointer;
}
div:hover {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
答案 3 :(得分:1)
Try This Code:
<div id='a' style="border:2px solid black" >
<h3>Hove On me</h3>
For 2000 milliseconds. You will get an alert.
</br>
</div>
$(document).ready(function(){
var delay=2000, setTimeoutConst;
$('#a').hover(function(){
setTimeoutConst = setTimeout(function(){
/* Do Some Stuff*/
alert('Thank You!');
}, delay);
},function(){
clearTimeout(setTimeoutConst );
})
})
</script>
DEMO:
答案 4 :(得分:1)
var st;
$(".inner_pic").mouseenter(function(e) {
var that = this;
st = setTimeout(function() {
alert('testing');
}, 3000);
}).mouseleave(function() {
clearTimeout( st );
alert('finish');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner_pic">
<h3>Picture Here - Hover me</h3>
</div>
答案 5 :(得分:1)
Assuming you have a div
with id
of myelement
, you can do this:
var divMouseOver;
$('#myelement').mouseover(function() {
divMouseOver = setTimeout(function() {
alert("3 seconds!"); //change this to your action
}, 3000);
});
$('#myelement').mouseout(function() {
if (divMouseOver) {
clearTimeout(divMouseOver);
}
});
BTW, tere's a helpful clarifying question re: using mouseenter
and mouseover
right here: Jquery mouseenter() vs mouseover(). Consider this when choosing which to use.