Hey I have a simple loop like this:
for(var i in nodes) {
var d = document.createElement('div');
d.className = 'box';
d.id = 'node' + i;
document.getElementById('node').appendChild(d);
document.getElementById('node'+ i).innerHTML = nodes[i].name;
document.getElementById('node'+ i).addEventListener('mousedown', function() {
var info = nodes[i]; display_parent(info);
}, false);
}
function display_parent(data){
console.log(data);
}
The problem is all the divs hold the same information aka the last one in the loop, i tried to assign the data to a local variable to info but it still does not work.
Any ideas how I can fix that?
It is due to closure in ‘mousedown’ event handler. You have to use something like this: