Add a specific event listener based on button text

Add a specific event listener based on button text
0.0 0

#1

I’m working on my Simon Game and was wondering if it is possible to add a specific event listener to a button based it’s innerText?

For example. I have a button saying “START GAME”. It gets clicked, a countdown from 3, 2, 1 occurs.
Then I want the button to switch to “RESTART” and I would like the functionality for the restart function to be set. Here’s my code thus far…

    startGame.addEventListener('click', () => {
      startGame.style.pointerEvents = "none";
      let time = 4;
      let countDown = () => {
               time--;
               startGame.innerText = time;
               
               if (time < 1) {
                 startGame.innerText = "GO!";
                  clearInterval(counter);
                  
                  setTimeout(() => {
                    startGame.innerText = "RESTART";
                    // do i detach the event handler and write a new one here?
                  }, 2000);
               }
            };
       const counter = setInterval(countDown, 1000);
     });

#2

If you can dream it, you can code it :sparkles: :star: :sparkles:

You’re thinking about this the wrong way, though. You don’t need to change the event handler, you just need to toggle your application’s state.

if (game.counter) {
    clearInterval(game.counter);
    this.innerText = "GO!";
} else {
    game.counter = setInterval(countdown, 1000);
    this.innerText = "RESTART";
}

#3

Interesting solution, thanks.

In the end I found another solution which I thought was pretty cool. Let me know if you think there are any drawbacks…

startGame.addEventListener('click', function() {
    if (this.innerHTML === 'START GAME') {
      countDownToBegin.call(this);
    } else if (this.innerHTML === 'RESTART') {
      this.innerHTML = 'START GAME';
      return;
    }
  });

#4

You need to clear the timer before you can start another. The way you have it now, you’ll be creating multiple timers.


#5

Yeah, but the button needs to reset, because I want the user to be able to restart the game if they wish. Hence, another 3, 2, 1 counter will be called…


#6

Sure, but unless the button stops the previous timer, the user could create a bunch of useless timers.


#7

Yeha, it does, I’ll link you to a simple codepen of what I have achieved, I think it works fine for what I wanted :slight_smile: