How can I trigger a click after a short delay in my HTML button?

There is a technology called duel, and it is used for ease of access on websites. It is used by people who can only move a device (such as a mouse.), And it works as follows. When freezing, the effect of freezing lasts longer than it allows to use as an example 1 second, after which the click function is triggered. I want to emulate this using jQuery for the elements of my button in my HTML.

+3
source share
3 answers
(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 a few clicks. (Thanks, Alnitak)

+6
source
var timer = null;
$('button').hover(mouseIn, mouseOut);

function mouseIn() {
   timer = setTimeout(triggerClick, 3000);
}

function mouseOut() {
   clearTimeout(timer );
}

function triggerClick() {
  $('button').trigger('click');
}

. , . , 1 , , .

+9

I knocked out a quick jQuery plugin to do what you requested.

Source (and demo) at http://jsfiddle.net/raybellis/tF833/

For reference here, the (current) code is as follows:

(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);
+5
source

All Articles