7

I am trying to do 2 different functionalities on one button on mousedown - up events. But its not working as i cant able to detect time on mousedown event.

var flag;  
$("#ClikerButton").mousedown(function(e){  
    //if mouse pressed more than 2 sec, then  
    // do func1 and set flag = true;  
         //else do nothing  
}).mouseup(function(e){  
//if flag == true, do nothing,  
//else do func2;  
});  
Alex
  • 9,313
  • 1
  • 39
  • 44

3 Answers3

7

You can use:

$(window).mousedown(function(e) {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        alert('mousedown > 2 sec');   
    }, 2000); 
}).mouseup(function(e) {
    clearTimeout(this.downTimer); 
});​

Fiddle: http://jsfiddle.net/simevidas/Pe9sq/2/

Reference: Detecting time on mousedown event

Community
  • 1
  • 1
talha2k
  • 24,937
  • 4
  • 62
  • 81
  • Thanks for quick reply. It's working fine now. I was not knowing mousedown event do have downTimer Variable. Please provide me if any more details of downTimer variable as well upTimer variable if available. Also provide me the coding used behing downTimer variable... – Jitendra Ahire May 02 '12 at 09:33
2

There is no 'jQuery' magic, just JavaScript timers.

var pressTimer

$("a").mouseup(function(){
  clearTimeout(pressTimer)
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... your code ...},1000)
  return false; 
});

here is the ref link https://stackoverflow.com/questions/2625210/long-press-in-javascript/2625240#2625240

Community
  • 1
  • 1
chhameed
  • 4,406
  • 4
  • 26
  • 44
1
var flag, flag2;
$("#ClikerButton").on({
    mousedown : function(){
       flag = new Date().getTime();
    },
    mouseup: function(){
       flag2 = new Date().getTime();
       var passed = flag2 - flag;
       console.log(passed); //time passed in milliseconds
    }
});​

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388