Search code examples
javascriptjqueryhoverdelayimage-gallery

jQuery/Javascript image gallery change image if hovered over for X but not if less than X


There might be a really simple answer for this but I've been pondering it for a while and can't think what it is.

I have an image gallery with thumbnails and one main image, I'd like to change the main image if the user hovers over a thumbnail for say 500ms but if they drag their mouse across the other thumbnails the time hovered would be less than 500ms so I don't want the image to change.

Thanks to everyone that answered, just figured it out and came back to post it but you'd all beat me to it, thanks again!


Solution

  • Well, you would have to use javascript timers with setTimeout() and clearTimeout().

    Basically you will create a timer when mouse enters you image - when the cursor goes out you clear it: if it hasn't run already, it xwill be cancelled.

    var timer;
    $('img').mouseenter(function() {
        timer = setTimeout(function() {
            // do something here
        }, 500);
    }).mouseleave(function() {
        clearTimeout(timer);
    });
    

    DEMO