Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() {  }); 
like image 840
Steffi Avatar asked Jan 29 '13 15:01

Steffi


2 Answers

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.

like image 75
Kevin B Avatar answered Oct 05 '22 00:10

Kevin B


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!');            }     } );  }()); 
like image 26
buley Avatar answered Oct 05 '22 00:10

buley