const - JS | lectureDOM & Events Fundamentals

Implementing Play Again

DOM & Events Fundamentals

We are now going to implement the play again functionality. I think you can take it as a challenge because it is already a great time for you to practice what you've been learning.

Before doing the challenge, I want us to hide back the secret number and only show it when the user has guessed the correct secret number. Because right now, as we load the page, the number becomes visible.

To fix that, just cut the below line of code which is right now outside of our event handler.

document.querySelector('.number').textContent = secretNumber;

and put it inside the condition (guess === secretNumber)

else if (guess === secretNumber) {
  document.querySelector('.number').textContent = secretNumber;

Now the game should be working as intended. Let's now implement the functionality of the again button, which will reset the entire interface. If you feel like you can take the challenge, then stop scrolling and when you are done, move on and check the solution else;, let's move on together.

Challenge Time

We will start by selecting the button and adding an event listener to it.

document.querySelector('.again').addEventListener('click', function () {
  score = 20;
  secretNumber = Math.trunc(Math.random() * 20) + 1;
  document.querySelector('.message').textContent = 'Start guessing...';
  document.querySelector('.score').textContent = score;
  document.querySelector('.number').textContent = '?';
  document.querySelector('.guess').value = '';
  document.querySelector('body').style.backgroundColor = '#22';
  document.querySelector('.number').style.width = '15rem';