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.
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);
}
});
On mouse down, set a timeout for 3 seconds in the future.
On mouse up, clear the timeout.
Seems like mouseup
/ mousedown
events and setTimeout
/ clearTimeout
is the way to do it:
var timer = null;
$(selector).on('mousedown', function(ev) {
timer = setTimeout(function() {
timer = null;
/* Do something */
}, 3000);
}.on('mouseup', function(ev) {
if (timer) {
clearTimeout(timer);
timer = null;
}
});
$('#div').on('mousedown', function(){
mousetimer.down();
}).on('mouseup', function(){
mousetimer.cancel();
});
var mousetimer = {
timer: null,
timing: false,
down: function(){
if(!timing)
{
mousetimer.timing = true;
mousetimer.timer = setTimeout(function(){
mousetimer.trigger();
}, 3000);
}
},
trigger: function(){
alert('do something');
mousetimer.cancel();
},
cancel: function(){
mousetimer.timing = false;
clearTimeout(mousetimer.timer);
}
};
Use a timeout of 3000ms.
Set the timeout on the mouse down event, clear it on the mouse up event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.