How to detect a long press on a div in Jquery?

Add a throttle that only allows the click to happen after 2 seconds of mousedown.

var timer;
$('div').on("mousedown",function(){
    timer = setTimeout(function(){
        alert("WORKY");
    },2*1000);
}).on("mouseup mouseleave",function(){
    clearTimeout(timer);
});

Edit: I added mouseleave too since if the mouse leaves the element and then triggers mouseup, it won't stop the timer.


Just watch both mousedown and mouseup and calculate the difference. Here's an example.

(function() { 

    // how many milliseconds is a long press?
    var longpress = 3000;
    // holds the start time
    var start;

    jQuery( "#pressme" ).on( 'mousedown', function( e ) {
        start = new Date().getTime();
    } );

    jQuery( "#pressme" ).on( 'mouseleave', function( e ) {
        start = 0;
    } );

    jQuery( "#pressme" ).on( 'mouseup', function( e ) {
        if ( new Date().getTime() >= ( start + longpress )  ) {
           alert('long press!');   
        } else {
           alert('short press!');   
        }
    } );

}());

In the two years since this question was asked an awesome plugin called jQuery Finger was invented:

http://ngryman.sh/jquery.finger/

$('div').on('press', function(e) {
    console.log(this, e);
});