Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show img when hovering (only if hover had a delay of 2 seconds)

Basically, I want my users to be able to hover a post title in my blog, and if they hover the title for 2 seconds, the image will show.

I am trying something like:

$('#post1').hover(function() {
  setInterval(function() {
    $('#img1').toggle();
  }, 2000); 
});

But it's not working as expecting. It keeps toggling after the initial 2s hover. How would you do it?

like image 874
Dan P. Avatar asked Jan 23 '26 01:01

Dan P.


1 Answers

var timeoutId;
$("#post1").hover(function() {
    if (!timeoutId) {
        timeoutId = window.setTimeout(function() {
            timeoutId = null; 
            $("#img1").toggle();
       }, 2000);
    }
},
function () {
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    else {
       $("#img1").toggle();
    }
});

Here is some working code and a jsfiddle to prove it works

like image 85
ntzm Avatar answered Jan 24 '26 21:01

ntzm