0

I modified a javascript code using setInterval to alternate between two messages using innerHTML. I tried document.write and it works. But innerHTML does not work.

// Create global interval and color variables
let interval;
let sentence;
let word;
let color = 'white';
// const word = document.querySelector("#one").innerHTML;
function startTogglingBg() {
  word = document.querySelector("#one").innerHTML;
  interval = setInterval(function() {
    if (color === 'white') {
      sentence = "Hey";
      color = 'red';
    } else {
      sentence = "You!";
      color = 'white';
    }
    // document.body.style.backgroundColor=color;
    // document.write(sentence);
    word = sentence;
  }, 1500);
}

function stopTogglingBg() {
  clearInterval(interval);
}

window.addEventListener('load', function() {
  btnStart = document.getElementById('start');
  btnStop = document.getElementById('stop');

  btnStart.addEventListener('click', startTogglingBg);
  btnStop.addEventListener('click', stopTogglingBg);
});
<button id="start">Start</button>
<button id="stop">Stop</button>

<p id = "one">Hello</p>

I expected the p tag value will change from the words "Hey" and "You!" every 1.5 seconds using setInterval. I tried document.write and it worked but the result is like this:

HeyYou!HeyYou!HeyYou!.......
1
  • 2
    You are never resetting the innerHTML simply changing word = sentence to document.querySelector("#one").innerHTML = sentence "works". But textContent is a more appropriate property here. Commented Aug 3, 2024 at 19:06

1 Answer 1

0

The problem is that you are just setting a new value for the word variable. However this does not update the text in the DOM. To do this, you need to set innerHTML or innerText of the element. Updated code:

// Create global interval and color variables
let interval;
let sentence;
let word;
let color = 'white';
// const word = document.querySelector("#one").innerHTML;
function startTogglingBg() {
  word = document.querySelector("#one").innerHTML;
  interval = setInterval(function() {
    if (color === 'white') {
      sentence = "Hey";
      color = 'red';
    } else {
      sentence = "You!";
      color = 'white';
    }
    document.querySelector("#one").innerHTML = sentence;
  }, 1500);
}

function stopTogglingBg() {
  clearInterval(interval);
}

window.addEventListener('load', function() {
  btnStart = document.getElementById('start');
  btnStop = document.getElementById('stop');

  btnStart.addEventListener('click', startTogglingBg);
  btnStop.addEventListener('click', stopTogglingBg);
});
<button id="start">Start</button>
<button id="stop">Stop</button>

<p id = "one">Hello</p>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.