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?
4 Answers
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/
- 182,163
 - 62
 - 281
 - 385
 
Off hand I would experiment with $("body").mousedown(function(){}) using jQuery and $("body").mouseup(function(){}). I guess you can start a timer which will call function in 2 to 3 seconds. If the mouseup event occurs, then you can cancel the timer. You could probably test it with a simple script but you might have to look at cases where the click might have occurred because a link or button was clicked on the page. But as a starting point I would experiment with the $("body").mousedown and $("body").mouseup. If I have chance I'll see if I can send a code sample.
- 510
 - 7
 - 19
 
- 10,153
 - 6
 - 47
 - 60
 
Check out this one. http://jsfiddle.net/b1Lzo60n/
Mousedown starts a timer that checks if mouse is still down after 1 second.
<button id="button">Press me</button>
<div id="log"></div>
Code:
var mousedown = false;
var mousedown_timer = '';
$('#button').mousedown(function(e) {
    mousedown = true;
    $('#log').text('mousedown...');
    mousedown_timer = setTimeout(function() {
        if(mousedown) {
            $('#log').text('1 second');
        }
    }, 1000);
}).mouseup(function(e) {
    mousedown = false;
    clearTimeout(mousedown_timer);
    $('#log').text('aborted');
});
- 922
 - 11
 - 11
 
Try this:
function WhateverYoudLikeToExecWithinNext3Seconds(){
    // Code goes here.
}
element.addEventListener('mousedown', function(){
    setTimeout(function(){WhateverIdLikeToExecWithin3Seconds();}, 3000);
}, false);
- 13,200
 - 6
 - 20
 - 26