When I click the event listener for the second time, new classes are added based on the condition, but the previous classes are not removed and/or reset.
Enter a year older than 1980 and see the result. Click 'Get Started' again and enter a year newer than 1980 (don't refresh the page) and the class attached to the new result doesn't change.
fakeEvent.addEventListener('click', function() {
let birthYear = prompt("What year were you born", "");
let currentYear = new Date().getFullYear();
let age = currentYear - birthYear;
if (age <= 40) {
result.innerHTML = `You entered ${age} years old.`;
result.classList.add('black');
} else {
result.innerHTML = `You entered ${age} years old.`;
result.classList.add('green');
}
})
.black { background: black; color: white; }
.green {background: green; color: yellow; }
h4 {
margin-top: 3rem;
}
<div class="container">
<button type="button" id="fakeEvent">Get Started</button>
<hr />
<div id="result"></div>
<h4>Enter a year older than 1980 and see the result. Click 'Get Started' again and enter a year newer than 1980 (don't refresh the page) and the class attached to the new result doesn't change.</h4>
</div>