xgrioux xgrioux - 1 month ago 20
Javascript Question

How do I toggle a class within a loop between a table row and map points?

I have 10 rows in a table that contains the address of each tag on a map. I am trying to add a click event to each tag on the map to it's corresponding table row. Instead of writing each click event separately I'm attempting to do it through a for loop. What's the best way to do this? The for loop below works for only the last iteration but not for all.

for (var i=0; i < 10; i++) {
var maptag = "#maptag";
var maprow = "#maprow";
$(maptag + +i).click(function() {
console.log('in the hole!');
$(maprow + +i).toggleClass('highlight');
return false;
});

Answer

You may need a closure

for (var i = 0; i < 10; i++) {
  var maptag = "#maptag";
  var maprow = "#maprow";
  (function(x) {  // IIFE
    $(maptag + +x).click(function() {
      console.log('in the hole!');
      $(maprow + +x).toggleClass('highlight');
      return false;
    })
  }(i))
}