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() { });
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!'); } } ); }());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With