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.
Maybe the clue is in this question:
Is there a situation where listener wouldn’t produce the button as
event.target
? How is this cheating?