0

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>

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What about the loading symbol in the tab why does it keep running? any ideas on that?
Not sure, it seems to be Firefox specific. My wild guess is that the function never returns since it is destroyed and the event handler hangs.
It keeps showing the loading icon until the document is closed via document.close();.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.