Oliver Ullman Oliver Ullman - 5 months ago 9
Javascript Question

Issue with this Javascript code (I think with the execution context)

On resize I want the code to run the first if statement: "I think this is too small". On the second resize I want it to run the first alternate: "I think this is too big".
It only runs one, is it because the variable adjustment is local only and doesn't stick around for the second time?



var counter = 0;
function message() {
if (counter == 0) {
document.write("I think this is too small");
counter = counter + 1;
} else if (counter == 1) {
document.write("I think this is too big");
counter = counter + 1;
} else {
confirm("Third Time's a charm");
}
}
window.addEventListener('resize', message, false);

<p>Text</p>




Answer

The problem is document.write. Never use document.write. You might think: "Oh, I want to write something to the document, so document.write seems perfect". Wrong, you have been fooled by its name. Even the specification says it's horrendous.

When you want to write something, use textContent, innerHTML or DOM methods.

var target = document.querySelector('p');
var counter = 0;
function message() {
  if (counter == 0) {
    target.textContent = "I think this is too small";
    counter = counter + 1;
  } else if (counter == 1) {
    target.textContent = "I think this is too big";
    counter = counter + 1;
  } else {
    target.textContent = "Third Time's a charm";
  }
}
window.addEventListener('resize', message, false);
<p>Text</p>

Comments