Request delay

How do I get the following code to delay half a second before the click event fires?

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

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

Thanks in advance

+3
source share
2 answers

You were on the right track with setTimeout:

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

Please note that this will trigger a click even if the mouse leaves the element in this half second. If you want to cancel the click, if the mouse leaves the element, you must 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");
        }
    })
;

data, , , , . , , (, , ), , clearTimeout .

+2

, , , setTimeout this. , - bind ( ECMA 5, , jQuery .proxy())...

jQuery('selector').mouseenter(function() {
    setTimeout(function() { jquery(this).trigger('click'); }.bind(this), 1000);
});

... () var:

jQuery('selector').mouseenter(function() {
    var el = jquery(this);
    setTimeout(function() { el.trigger('click'); }, 1000);
});
0

All Articles