DannyMoshe
DannyMoshe

Reputation: 6265

How to have an event trigger every time a user presses a key in javascript

First of all, I'm new to Javascript. I would like to have an event repeat itself every time a user presses a key in Javascript. See the sample code below:

<script>
    document.addEventListener('keydown', function(event){
        if(event.keyCode == 39) {
            document.write('Right was pressed');
        }
    })
</script>

When this code is run and the right arrow key is pressed, the statement is only printed once. I would like to have the event register multiple times, as many times as the user presses the key. Any suggestions?

Upvotes: 1

Views: 1681

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

The event is fired every time you press the key (and repeated if you hold the key down), but document.write() will every time override the content so it looks like nothing change, you could use innerHTML instead (just to see the effect) :

document.addEventListener('keydown', function(event){
  if(event.keyCode == 39) {
    //Not recommended as 'T.J. Crowder' mentioned in the comment
    document.body.innerHTML += 'Right was pressed <br>';
  }
})

You could use console.log() to debug and make sure the event was invoked :

document.addEventListener('keydown', function(event){
  if(event.keyCode == 39) {
    console.log('Right was pressed');
  }
})

Upvotes: 2

Xinzoop
Xinzoop

Reputation: 111

Actually it indeed triggered multiple times. The problem is document.write would clear the DOM.

This example works well for me.

script:

var counter = 0;
document.addEventListener('keydown', function(event){
    if(event.keyCode == 39){
    ++counter;
    document.getElementById("demo").innerHTML = "Key downed " + counter;
  }
});

html:

<p id="demo">

</p>

Upvotes: 1

Related Questions