I have a for loop which creates divs with new IDs, and then adds events to them using addEventListeners, with the IDs being the loop variable.
It's supposed to add the event to all the created divs, but what ends up happening is that the event is only added to the last div (in this case the div with id 2, since that's the last value i has in the loop).
`
for(let i=0; i<weaponarray.length; i++){
(function(){
let j = i;
document.getElementById("right").innerHTML +=
"<div class='itemcontainer' id="+j+" draggable='true'><div class='item'></div><div class='itemlabel'>"+weaponarray[j].name+"</div></div>";
let weaponstring = JSON.stringify(weaponarray[j]);
document.getElementById(j).addEventListener("dragstart", (ev) => onDrag(ev, "text", weaponstring));}());
}
`
I've looked for answers, for example on these posts (1, 2). I've read about closures and variable hoisting, and I've tried implementing solutions from the mentioned threads, for example by replacing var with let, putting all the code inside the loop into a function, and even declaring a new variable local to said function (j). But despite all of this, it still doesn't seem to work.
Here is all of my JS and HTML, although I don't think the rest of my JS is very relevant, since the very same thing happened even when I replaced the (ev) => onDrag(ev, "text", weaponstring)
function in my code with simple console.log(j);
.
`
function onDrag(ev, datatype, data){
ev.dataTransfer.setData(datatype, data)
console.log(ev.dataTransfer.getData(datatype));
}
let weaponcount = 0;
let weaponarray = [];
function Weapon(name, archetype, element, range, stability) {
this.name = name;
this.archetype = archetype;
this.element = element;
this.stats = {
range: range,
stability: stability
};
weaponcount++;
weaponarray.push(this);
}
const Summoner = new Weapon("The Summoner", "Auto Rifle", "Solar", 93, 62);
const GnawingHunger = new Weapon("Gnawing Hunger", "Auto Rifle", "Void", "78", "79");
const Austringer = new Weapon("Austringer", "Hand Cannon", "Kinetic", "67", "53");
for(let i=0; i<weaponarray.length; i++){
(function(){
let j = i;
document.getElementById("right").innerHTML +=
"<div class='itemcontainer' id="+j+" draggable='true'><div class='item'></div><div class='itemlabel'>"+weaponarray[j].name+"</div></div>";
let weaponstring = JSON.stringify(weaponarray[j]);
document.getElementById(j).addEventListener("dragstart", (ev) => onDrag(ev, "text", weaponstring));}());
}
`
`
<div id="container">
<div id="banner">
<h1>aaa</h1>
</div>
<div id="left"></div>
<div id="right"></div>
</div>
`