1

I'm new to this so i guess i'm missing something simple. The foor loop works fine but inside it i get an undefined variable

 var categories_info = ["historia","excelencia","arte","social","instalaciones","padres","familia"];
for ( var i = 0; i < categories_info.length; i++) {
  $("#showMe-"+categories_info[i]).click(function(){
    $(".info."+categories_info.[i]).addClass("info-show");
    console.log(".info."+categories_info[i]); //debug is undefinded
  });
};
Turqueso
  • 432
  • 11
  • 19

2 Answers2

3

You need to create a closure like

var categories_info = ["historia", "excelencia", "arte", "social", "instalaciones", "padres", "familia"];
for (var i = 0; i < categories_info.length; i++) {
    (function(i) {
        $("#showMe-" + categories_info[i]).click(function() {
            $(".info." + categories_info[i]).addClass("info-show");
            console.log(".info." + categories_info[i]); 
        });
    })(i);
};

This method is known as an IIFE

Basically, what was happening is the variable i was unavailable to the callback when the actual click happened.

However, by passing i in a self-executing anonymous function, you have created a closure which will preserve i and is accessible to the click handler.

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Thanks! i didn't know about this, thank you for the info about the method. I see in console.log what I expected but i'm getting `Unexpected token [` on this line `$(".info." + categories_info.[i]).addClass("info-show");` wich seems really odd – Turqueso May 29 '15 at 14:32
  • @ShairNash, it was a syntax error with an extra `.`. Try my updated answer and let me know if it still doesnt work – AmmarCSE May 29 '15 at 14:34
  • I see the dot now! how did I miss it? Thanks a lot! – Turqueso May 29 '15 at 14:58
1

Use a closure. Change:

$("#showMe-"+categories_info[i]).click(function(){
    $(".info."+categories_info.[i]).addClass("info-show");
    console.log(".info."+categories_info[i]); //debug is undefinded
});

To:

(function( i ) {
    $("#showMe-"+categories_info[i]).click(function(){
        $(".info."+categories_info.[i]).addClass("info-show");
        console.log(".info."+categories_info[i]);
    });
})( i );
PeterKA
  • 24,158
  • 5
  • 26
  • 48