Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire an event after n seconds of maintained click? - jQuery/Javascript

I am sure I am not the first looking for this, but I did not find any solution to my problem..

I am looking for a way to fire an event after and only after a 3 seconds maintained click. I tried with javascript setInterval() function with mouseup/mousedown Jquery events but it did't work.

Someone has an idea ?

I have a div, I keep the mouse button down for 3 seconds, and something will be fired. 3 seconds timer must be reinitialized every time.

like image 731
Pier-Alexandre Bouchard Avatar asked Feb 21 '12 02:02

Pier-Alexandre Bouchard


People also ask

How do I call a function after 2 seconds in jQuery?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.

How to trigger form in jQuery?

jQuery submit() Method The submit event occurs when a form is submitted. This event can only be used on <form> elements. The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.


1 Answers

Call setTimeout() to perform your action after 3000 milliseconds, storing the identifier from setTimeout() into a variable scoped above the function. On the element's mouseup(), clear the timeout if it exists via clearTimeout().

var divMouseDown;
$('#div-id').mousedown(function() {
  divMouseDown = setTimeout(function() {
     // Do timeout action...
  }, 3000);
});
$('#div-id').mouseup(function() {
  if (divMouseDown) {
    clearTimeout(divMouseDown);
  }
});
like image 182
Michael Berkowski Avatar answered Sep 24 '22 14:09

Michael Berkowski