this post was submitted on 09 Oct 2021
1 points (100.0% liked)

learnjavascript

160 readers
1 users here now

  1. Be Welcoming. n00bs are welcome here. Negativity is not.

  2. Include Context If you’re asking for help, include enough information for others to recreate your problem.

  3. No unvetted self promotion Message the mods first.

founded 4 years ago
MODERATORS
 

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.


no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here