How can I trigger click after a short delay in my HTML button?
There is a technique called duell and it is used for accessibility reasons in websites. It is used from people that can only move a device (i.e mouse.) and it works like this. On hover effect hovering lasts longer than lets se as an example 1 sec then the click function is triggered. I want to emulate this with jQuery for my button elements i开发者_如何转开发n my HTML.
var timer = null;
$('button').hover(mouseIn, mouseOut);
function mouseIn() {
timer = setTimeout(triggerClick, 3000);
}
function mouseOut() {
clearTimeout(timer );
}
function triggerClick() {
$('button').trigger('click');
}
This solution uses timers. Starts a timer when you hover over the element and clears it when you stop hovering over it. Obviously this only works for 1 button, but you could easily modify it to work for all buttons on your page.
(function() {
var clearTimeout = function(b) {
window.clearTimeout($(b).data("hoverTimer"));
}
$("button").hover(function() {
var button = $(this);
button.data("hoverTimer", window.setTimeout(function() {
button.trigger("click");
}, 1000));
}, function() {
clearTimeout(this)
}).click(function() {
clearTimeout(this)
});
})();
Edited to avoid multiple clicks. (Thanks, Alnitak)
I knocked out a quick jQuery plugin to do what you asked.
Source (and demo) at http://jsfiddle.net/raybellis/tF833/
For reference here, the (current) code looks like:
(function($) {
$.fn.duell = function() {
return this.each(function() {
var timer = null;
var el = this;
var stopTimer = function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
var startTimer = function() {
stopTimer();
timer = setTimeout(function() {
$(el).click();
}, 1000);
};
// make sure other clicks turn off the timer too
$(el).click(stopTimer);
// handle mouseenter, mouseleave
$(el).hover(startTimer, stopTimer);
});
};
})(jQuery);
精彩评论