I have been reading this book “Modern Javascript for the Impatient”, chapter “Object-Oriented Programming”. At the end there is an “Exercise” section. This is a question from it I need help answering:


Harry tries this code to toggle a CSS class when a button is clicked:

const button = document.getElementById('button1')
button.addEventListener('click', function () {
  this.classList.toggle('clicked')
})

It doesn’t work. Why?

Sally, after searching the wisdom of the Internet, suggests:

button.addEventListener('click', event => {
  event.target.classList.toggle('clicked')
})

This works, but Harry feels it is cheating a bit. What if the listener hadn’t produced the button as event.target? Fix the code so that you use neither this nor the event parameter.


  • Umo
    link
    fedilink
    arrow-up
    3
    ·
    3 years ago

    Well, you can reuse the reference to your button.

    button.addEventListener('click', function () {
      button.classList.toggle('clicked')
    })
    

    But I’m not sure that this is the expectet answer. I also don’t understand why event.target should be discouraged.

    • 2br02bOP
      link
      fedilink
      arrow-up
      1
      ·
      3 years ago

      Maybe the clue is in this question:

      This works, but Harry feels it is cheating a bit.

      What if the listener hadn’t produced the button as event.target?

      Is there a situation where listener wouldn’t produce the button as event.target? How is this cheating?