March 26, 2012
How can i do button on hold for two second call function1 if less then two second call function2?
Question by YumYumYum
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 then 2 seconds then callfunction1
, if the button was pressed less then 2 seconds then callfuntion2
.
var clickDisabled = false;
function clickLocker() {
/* @Button: 2 seconds */
clickDisabled = true;
setTimeout(function(){clickDisabled = false;}, 2000);
}
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 }
$('.button').live("click",function()
{
if (clickDisabled) {
alert("locked for 2 second");
return;
}
clickLocker();
});
Answer by Starx
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