Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query delay mouseenter

Tags:

jquery

delay

How would I get the following code to delay for half a second before triggering the click event?

jQuery('selector').mouseenter(function() { jQuery(this).click() });

I tried adding .delay & setTimeout() but can't get them to work.

Thanks in advance

like image 898
nihilster Avatar asked Feb 24 '26 01:02

nihilster


1 Answers

You were on the right track with setTimeout:

jQuery('selector').mouseenter(function() {
    var $elm = jQuery(this);
    setTimeout(function() {
        $elm.click()
    }, 500);
});

Note, though, that that will fire the click even if the mouse leaves the element within that half second. If you want to cancel the click if the mouse leaves the element, you have to remember the timer handle and cancel:

jQuery('selector')
    .mouseenter(function() {
        var $elm = jQuery(this),
            timer = $elm.data("timer");
        if (timer) {
            clearTimeout(timer);
        }
        $elm.data("timer", setTimeout(function() {
            $elm.click()
        }, 500));
    })
    .mouseleave(function() {
        var $elm = jQuery(this),
            timer = $elm.data("timer");
        if (timer) {
            clearTimeout(timer);
            $elm.removeData("timer");
        }
    })
;

That uses data to save a timer handle when the mouse enters the element, and if the mouse leaves the element, it cancels the timer. It's okay that we will cancel timers that don't exist (e.g., if the timer fires before the mouse leaves the element), that's a normal case, the clearTimeout call is just ignored.

like image 158
T.J. Crowder Avatar answered Feb 26 '26 23:02

T.J. Crowder