I would like to execute some function when the user presses for 2 seconds
on a div.
Is it possible ?
Here is my code to detect the click on the div
$('div').mousedown(function() {
});
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!');
}
} );
}());