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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<title>Timer</title>
</head>
<body>
<main>
<button id="start">Start</button>
<button id="stop">Stop</button>
<p id = "one">Hello</p>
</main>
<script>
// 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);
});
</script>
</body>
</html>
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!…….
Thanks.
New contributor
anonymous is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.