Udacity Javascript patterns Issue

Hey there !

I can’t tell if it’s okay to post JS stuff that isn’t related to FCC, but I think this is still relevant as a learning process.

Somebody posted a link to Udacity Javascript patterns and I had a lot of fun practicing Vanilla JS instead of using Jquery for such projects. I’m starting to have some troubles with the addEventListener method, allocating different variables to clickable elements of a list.

What I need to achieve is a list of cat names, and each of the links makes the appropriate cat data appears on the right side.

I have read a bit that in order to allocate the current “i” value within a for loop, you’d have to use an IIFE function in addEventListener, but so far, the first element fires away on page load, and nothing responds to clicks after that.

Problem is around line 34 : https://codepen.io/Mizujin/pen/rLOexW

Your help is greatly appreciated !

Okay, I fixed it. It was something I’ve read about yesterday while having my eyes slowly closing :wink:

It’s all about closures, again !

Instead of this :

element.addEventListener("click", function(id) {
  console.log(id); // nope

This worked like a charm :

element.addEventListener("click", (function(id){
      return function() {
        console.log(id); // works !

Lesson learned : I still got a bunch to learn concerning the magic behind closures :smiley:

1 Like