Search code examples
jquerymousedownmouseup

Move div when you click and hold a button


Basically I want my player to move when I click and hold a button using JQuery's .mousedown function. The problem is, the player doesn't continously move left, he just moves once. I want him to keep moving left until I mouseup.

Here's my code:

$('#arrowRight').mousedown(function() {
      $('#player').animate({'left':'+=20px'});
});

Any ideas?


Solution

  • Try this:

    var isDown = false;
    $arrowRight = $("#arrowRight");
    $arrowLeft = $("#arrowLeft");
    $arrowRight.mousedown(function(){isDown = true;});
    $arrowLeft.mousedown(function(){isDown = true;});
    $(document).mouseup(function(){
        if(isDown){
            isDown = false;
        }
    }); 
    
    $arrowRight.mousedown(function() {movePlayer('+=20');});
    $arrowLeft.mousedown(function() {movePlayer('-=20');});
    
    function movePlayer(intMovement){
      $( "#player" ).animate({
            'left': intMovement +'px'
      }, 100, function() {
          if (isDown){
              movePlayer(intMovement);
          }
      });
    }
    

    Check JSFiddle Demo