Add a specific event listener based on button text

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

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) {
    this.innerText = "GO!";
} else {
    game.counter = setInterval(countdown, 1000);
    this.innerText = "RESTART";

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') {;
    } else if (this.innerHTML === 'RESTART') {
      this.innerHTML = 'START GAME';

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

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…

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

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:

1 Like