Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyDown doesn't continuously fire when pressed and hold

I have this Plunkr,

This contains a div, on which I bind a keydown event. On pressing right or left arrow, the div should start moving.

This works, in all browsers, but when the key is pressed and hold, the first keydown event is fired immediately (div once moves), and it waits for a time gap, and then it continues to move.

So this means the keydown event is once fired, then the browser waits to detect if there is a subsequent keyUp event as well, then after a short time (when there is no keyup), it continues to fires keydown events.

(to see the problem, focus on window, press right arrow and hold, div should move once 5px, then wait, and then again continue to move)

Question: Is there a way around, so I can just keep the key pressed, and div should immediately start moving, without waiting to detect subsequent keyup (once)?

$(function() {
  $(window).keydown(function(e) {
    console.log(e.keyCode)
    if (e.keyCode == 39)
      move(5, 'left', $('.mover'))
    else if (e.keyCode == 37)
      move(-5, 'left', $('.mover'))
  })

})

function move(offset, direction, target) {
  console.log($(target))
  $(target).css(direction, (parseInt($(target).css(direction)) + offset) + 'px')
}
.mover {
  height: 50px;
  width: 50px;
  display: inline-block;
  background: black;
  position: absolute;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='mover'></div>
like image 608
Naeem Shaikh Avatar asked Feb 20 '26 06:02

Naeem Shaikh


1 Answers

I would suggest something on a timeout, like this

http://codepen.io/kevrowe/pen/qEgGVO

$(function() {
  var direction,
      movingTimeout = -1;

  $(window).on('keydown', function(e) {    
    if (e.keyCode == 39) {
      direction = 'right';
    } else if (e.keyCode == 37) {
      direction = 'left';
    }  

    startMoving(direction);
  });

  function stopMoving() {
    clearTimeout(movingTimeout);
    movingTimeout = -1;
  }

  function startMoving(direction) {
    if (movingTimeout === -1) {      
      loop(direction);
    }
  }

  function loop(direction) {
    move(direction === 'left' ? -5 : 5, $('.mover'));
    movingTimeout = setTimeout(loop, 10, direction);
  }

  function move(offset, $target) {
    $target.css('left', (parseInt($target.css('left')) + offset) + 'px')
  }

  $(window).on('keyup', function(e) {    
    stopMoving();
  });
})
like image 149
kev.rowe Avatar answered Feb 22 '26 20:02

kev.rowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!