Reputation: 2664
Im struggling to create a functionality which keeps on incrementing css property of an element when someone presses and 'holds' a button.
something like this:
var timeoutId = 0;
$('#left').mousedown(function() {
timeoutId = setTimeout(myFunction, 1000);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
function myFunction() {
var left = parseInt($("#menuElem").css('left')) + 10;
$("#menuElem").animate({
'left' : left + 'px'
});
}
I want that myFunction to be repeated again and again until mouseup or mouseleave event is fired.
cheers
Upvotes: 1
Views: 2217
Reputation: 767
According to this SO question you can't detect the current up or down state of a key, only monitor the respective events.
So you'd need something like this i guess
var mouseIsDown = false;
$('#button').mousedown(function(){
mouseIsDown = true;
incrementValue;
});
$('#button').mouseup(function(){
mouseIsDown = false;
});
Then have that function be all like:
function incrementValue() {
whatever++;
if(mouseIsDown){
setTimeout("incrementValue()", 20);
}
}
On mouse down, the mouseIsDown
var gets set to true, and it starts a loop that continues to increment (at whatever interval you set the time parameter to in setTimeout()
) until mouseIsDown
is false, which happens on mouseup.
Upvotes: 2