Pregunta

I am showing the image preview when hovering over the image. Now I do keep the interval before displaying the preview image. say I set the delay as 1 sec, and within this if I dragged the mouse out of image, it still displays the preview since it is triggered during the mouse enter . How to fix this?

I need to display a preview only on hover after 1sec delay and not if the mouse is not with in the image?

¿Fue útil?

Solución 2

A basic skeleton using setTimeout() can be

var timer;
$('img').hover(function () {
    timer = setTimeout(function () {
        //do your stuff here
        $('div').show();

        timer = undefined;
    }, 1000);
}, function () {
    if (timer) {
        clearTimeout(timer);
        timer = undefined;
    } else {
        //hide the preview
        $('div').hide();
    }
})

Demo: Fiddle

Otros consejos

On jQuery 1.9+, you could use delay/finish:

DEMO jsFiddle

$("#preview").hover(function(){
    $("img").delay(1000).show(0); // passing 0 to show() will put animation in queue
}, function(){
    $("img").finish().hide(); // finish() will clear any previous delay(), despite what argues the DOC
});

Assign the setTimeout to a variable on mouseover event like this:

var timer = setTimeout(function() { doSomething(); }, 1000);

And then clear it on mouseout event so it doesn't show when you hover out of it:

clearTimeout(timer);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top