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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With