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.


  • 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?