Spot the bug - #123: Buzzer Button

Why does my party buzzer play before anyone clicks it?

const buzzer = document.querySelector("#buzzer");

function playHonk() {
  document.body.classList.toggle("party-mode");
}

buzzer.addEventListener("click", playHonk());

Reply with what is broken and how you would fix it.

The problem is this line::index_pointing_at_the_viewer:

buzzer.addEventListener("click", playHonk());

playHonk() is being called immediately when the page loads. Its return value is then passed to addEventListener().

You need to pass the function itself:

buzzer.addEventListener("click", playHonk);

Then playHonk will only run when the buzzer is actually clicked.

Easy mistake to make with event listeners!

1 Like

yo @Apexcodes, nice catch! you’re definitely looking in the right spot.

we’ll drop the full answer later today, so keep an eye out.

That’s a classic one! You’re right, playHonk() immediately calls the function.

Here’s a quick tutorial on how event listeners work: https://www.kirupa.com/html5/setting_up_event_listeners.htm

Lol yeah, classic mistake. my first unity project was full of those.

Ha fair

The is_pressed flag is set to true on the initial press, but there’s no corresponding false assignment when the button is released. It will stay true forever.

Spot the Bug answer: The event listener is immediately invoking the playHonk function instead of referencing it.

The fix:

buzzer.addEventListener("click", playHonk);

Why:
When you add parentheses after a function name in JavaScript, you are calling that function immediately. The addEventListener expects a function reference as its second argument, but it receives the result of playHonk() (which is undefined) right away. This causes playHonk to execute once when the script loads, and then nothing happens on click.


Got it: @Apexcodes :trophy:

First-answer leaderboard

  1. @kirupa - 5 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @Apexcodes - 2 (firsts)
  4. @emmawalter5 - 1 (first)

Ha, nice catch. I’ve definitely made that mistake before, especially when trying to quickly prototype something.