Search code examples
javascriptjquerymousedown

Mousedown Timer using JavaScript/jQuery


How can I know how long a user has been holding the mouse button down (anywhere on a webpage)? I want to execute a function when the user held the mouse button for at least 2-3 seconds (preferably cancelling the mouse down in the process). Is this possible?


Solution

  • Here you go:

    $(window).mousedown(function(e) {
        clearTimeout(this.downTimer);
        this.downTimer = setTimeout(function() {
            // do your thing 
        }, 2000);
    }).mouseup(function(e) {
        clearTimeout(this.downTimer);
    });
    

    Live demo: http://jsfiddle.net/simevidas/Pe9sq/2/