How to add delay to jquery mouseover? [duplicate]

I have a bunch of images on one page and I am using the following to trigger an event:

$('.img').on('mouseover', function() {
 //do something

});

Is there some way to add a delay such that if a user hovers for maybe 1 second, then it does "//do something" or actually triggers the "mouseover" event?

Answers:

Answer

You can use setTimeout

var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
  setTimeoutConst = setTimeout(function() {
    // do something
  }, delay);
}, function() {
  clearTimeout(setTimeoutConst);
});
Answer

You could do that using a setTimeout along with a clearTimeout if the user leaves too soon:

var timer;
var delay = 1000;

$('#element').hover(function() {
    // on mouse in, start a timeout

    timer = setTimeout(function() {
        // do your stuff here
    }, delay);
}, function() {
    // on mouse out, cancel the timer
    clearTimeout(timer);
});
Answer

Use a timer and clear it when they mouseout incase they leave within 1000ms

var timer;

$('.img').on({
    'mouseover': function () {
        timer = setTimeout(function () {
            // do stuff
        }, 1000);
    },
    'mouseout' : function () {
        clearTimeout(timer);
    }
});
Answer

I was looking for something like this as well, but with a secondary delay as well. I took one of the answers here and expanded upon it

This example shows a div after X seconds of mouseover and hides it after X seconds of mouseout. But disables if you hover over the shown div.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.foo{
  position:absolute; display:none; padding:30px;
  border:1px solid black; background-color:white;
}
</style>
<h3 class="hello">
  <a href="#">Hello, hover over me
    <span class="foo">foo text</span>
  </a>
</h3>


<script type="text/javascript">
var delay = 1500, setTimeoutConst, 
    delay2 = 500, setTimeoutConst2;
$(".hello").mouseover(function(){
  setTimeoutConst = setTimeout(function(){
    $('.foo').show();
  },delay);
}).mouseout(function(){
  clearTimeout(setTimeoutConst );
  setTimeoutConst2 = setTimeout(function(){
    var isHover = $('.hello').is(":hover");
    if(isHover !== true){
      $('.foo').hide();
    }
  },delay2);
});
</script>

Working example

Answer

You can use jquery .Delay like this (not tested):

$("#test").hover(
    function() {
        $(this).delay(800).fadeIn();
    }
);

http://api.jquery.com/delay/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.