0

I'm a beginner in Javascript, and I'm struggling to understand some of its functionalities. I can't figure out how the For loop is behaving in my code :

I have two HTML paragraphs, I want to attach to both of them a click listener to change their color to red using a For loop.

var paragraphs = document.querySelectorAll('p')

for (var i = 0; i < paragraphs.length; i++) {
  p = paragraphs[i]
  p.addEventListener('click', function(e) {
    p.classList.toggle('red')
  })
}

Here, only the last paragraph gets colored to red when I click on any one of them.

Someone gave me a solution that I didn't understand at all :

var paragraphs = document.querySelectorAll('p')

for (var i = 0; i < paragraphs.length; i++) {
  (function(p) {
    p.addEventListener('click', function(e) {
      p.classList.toggle('red')
    })
  })(paragraphs[i])
}

This is working, but I have no clue what is going on in this code.

Can someone help me by telling me why my first code isn't working (even if it seems correct), and explaining just a little bit what's going on in the second code.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dwix
  • 1,139
  • 3
  • 20
  • 45
  • 2
    In short: in your first snippet all event handlers reference __the same__ variable `p`, which is reassigned on every iteration. When it is time to execute the handlers, all point to the last value `p` had. Whereas in the second snippet value of current paragraph is __copied__ to the handler. The concept is called __closures__ and being able to understand it is crucial. – Sergio Tulentsev Oct 29 '16 at 20:05
  • @SergioTulentsev Thank you a ton, that points me to the right direction. – Dwix Oct 29 '16 at 20:06

0 Answers0