Skip to content Skip to sidebar Skip to footer

How Can I Do Button On Hold For Two Second Call Function1 If Less Then Two Second Call Function2?

I have this button which is not working correctly for hold button for a period (but it works like click only). Where i was trying to do if the button is hold for greater/equal the

Solution 1:

I think this solution should work. I have not tested it but it should give you the right idea.

var startTime;

function callfunction1() { // you have hold he button for greater then or equal 2 second } 
function callfunction2() { // you have hold the button less then 2 second } 

function buttonDownEvent() { 
  var Time = new Date();
  startTime = Time.getTime();
}

function buttonUpEvent() { 
  if(new Date().getTime() - startTime < 2000)
    callfunction2()
  else
    callfunction1()
}

$('.button').live("mousedown",function()
{ 
  buttonDownEvent();
});

$('.button').live("mouseup",function()
{ 
  buttonUpEvent();
});

Solution 2:

Listen for both events, mousedown and mouseup, measuring the time between both:

     var timeDown;
     var timeUp;
     $('.button').live("mousedown",function(){
            timeDown = event.timeStamp;
     });
     $('.button').live("mouseup",function(){
            timeUp = event.timeStamp;
            time = timeUp-timeDown;
            if (time>2000){
                function1();
            }else{
                function2();
            }


     });

please note that event.timeStamp wont work well in firefox. For firefox you can do (new Date).getTime();


Solution 3:

You can do this using events to the mouseup and mousedown events and timing the difference between them. Also, you need to remember which element caused the click - if the user released the mouse on a different element then it should just do the "non 2-second hold" function. A JSFiddle showing this working is available here: http://jsfiddle.net/35rw3/6/.


Solution 4:

That was a great suggestion from slash. This is how you can do this

var clickstart;
var clickstop;
$("a").on('mousedown', function(e) {    
    clickstart = e.timeStamp;
}).on('mouseup', function(e) {
    clickstop = e.timeStamp- clickstart
    if(clickstop >= 2000) two()
    else one();
});

Demo


Updates:

It might be necessary to track the mouse movement like @MarkRhodes wrote in his comments. So for that, check this update


Post a Comment for "How Can I Do Button On Hold For Two Second Call Function1 If Less Then Two Second Call Function2?"