Skip to content Skip to sidebar Skip to footer

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 sec

Solution 1:

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/


Solution 2:

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.


Solution 3:

Try this:

function WhateverYoudLikeToExecWithinNext3Seconds(){
    // Code goes here.
}

element.addEventListener('mousedown', function(){
    setTimeout(function(){WhateverIdLikeToExecWithin3Seconds();}, 3000);
}, false);

Solution 4:

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');
});

Post a Comment for "Mousedown Timer Using JavaScript/jQuery"