1

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

Varinder
  • 2,634
  • 1
  • 17
  • 20
  • 1
    what are you struggling on exactly see [here](http://stackoverflow.com/a/4080508/1114171) for detecting click->hold-down then just check out `.css()` – T I Jan 29 '12 at 11:13
  • apologies for not being clear.. updated my question with the link you provided -cheers. – Varinder Jan 29 '12 at 11:31

1 Answers1

2

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.

Community
  • 1
  • 1
sicks
  • 757
  • 8
  • 23
  • hello, ive implemented your code -for some reasons it doesent repeat the incrementValue() function, firebug says incrementValue() is not defined on line 'setTimeout("incrementValue()", 20);' any ideas? -cheers. – Varinder Jan 30 '12 at 00:02
  • Remove the quotes maybe? I haven't tested this, just threw it together to demo the idea, and point you in the right direction. – sicks Feb 02 '12 at 09:27