0

I am trying to add Action Listener to several divs created dynamically. I have to use loop to add action listener to them.

This is the code:

for (var i = 0; i < mapData.length; i++) {

var marker = new google.maps.Marker({
            position: new google.maps.LatLng(mapData[i].lat, mapData[i].long),
            icon: circleMaker,
            map: map
        });

        var temp = mapData[i].id;
        var temp_marker = marker;

document.getElementById('sensor_'+temp).addEventListener('mouseover', function() {
          //temp_marker.setIcon(circleMakerHi);
          console.log("sensor: "+temp);
        }, false);
}
}

This loops prints only the last value of the loop. If sensor_2 div is hovered, then it should print sensor: 2 but it prints sensor: 7 where 7 is the mapData.length.

Arjun
  • 16
  • 1
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Phil May 25 '16 at 02:28
  • Quick answer, try `console.log('sensor:', this.id.split('_')[1])` – Phil May 25 '16 at 02:29

0 Answers0