OAH
OAH

Reputation: 335

Understanding this event handler in Javascript

I expect the code below to increment the variable counter each time the event is fired i.e., when the down key is pressed, however it does not. The code increments only once and then nothing happens even if I press the down key.

Can you explain why is it happening?

Also the Firefox's tab keeps showing the loading circle when the event fires, why is that? Moreover is there a lifetime for the event listener i.e., does it expire when the </script> is reached?

<html>
<head>
<body>

<script>
var counter=0;
addEventListener("keydown",function(){
counter++;
document.write(counter);
});
</script>
</body>
</html>

Upvotes: 0

Views: 57

Answers (2)

Joe Skora
Joe Skora

Reputation: 14911

Lukas described the problem correctly, the following modified version of your example includes a <div> to be written to and changes to the event listener to write to the tag instead of the overwriting the DOM.

<html>
<head>
<body>
<script>
  var counter=0;
  addEventListener("keydown",function(){
    counter++;
    document.getElementById("target").innerHTML = counter;
  });
</script>
<div id="target"></div>
</body>
</html>

Upvotes: 1

Lukas Steiblys
Lukas Steiblys

Reputation: 76

document.write() actually overwrites all the current contents of the page so your code will run only once and your HTML code afterwards will contain only one character "1". That means your DOM will be destroyed and there will be no more JavaScript code to run.

What you probably want to do is update the contents of a specific element instead of overwriting all your document.

Upvotes: 1

Related Questions