ravip0711 ravip0711 - 6 months ago 49
jQuery Question

jQuery using keydown/keyup/keypress event to fire only one time instead of multiple times when key held down

I'm trying to add the same div with same class after the first one on each keypress on the board.


  1. Using keypress, when the user holds down the key, it causes the event to fire when its held down (and continues to run). I want to stop that and only fire the function once on a keypress even if the key is held down.





<div class="player1"></div>




$(document).on('keydown', function() {
$('.player1:last').after('<div class="player1">Go!<div>');
})

Answer
  1. Using keypress, when the user holds down the key, it causes the event to fire when its held down (and continues to run). I want to stop that and only fire the function once on a keypress even if the key is held down.

You can use .one() to attach keydown event, at keyup event re-attach keydown event using .one() again, which should prevent keydown handler from being called when key is held down.

function handleKeyDown() {
    $('.player1:last').after('<div class="player1">Go!<div>');
}

var d = $(document);

d.one('keydown', handleKeyDown)
.on("keyup", function() {
  d.one("keydown", handleKeyDown)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="player1"></div>