0

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>

1 Answer 1

1

You can simply clear the classList out before making the change

  result.classList.remove('black', 'green');

fakeEvent.addEventListener('click', function() {
  let birthYear = prompt("What year were you born", "");
  let currentYear = new Date().getFullYear();
  let age = currentYear - birthYear;
  result.classList.remove('black', 'green');
  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. Enter a year newer than 1980 and the class attached to the new result doesn't change.</h4>
</div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.