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!.......