I'm trying to create a playlist of songs. To create the playlist I created an update function called checklist()
. Which receives an array parameter called playlist
of songs currently in the playlist. I do also want to add a removebutton which refers to every song in the playlist. However, adding the addEventListener in an iterative way only adds functionality to the last item iterated over. I guess the event listeners are overwritten every iteration and it is a common mistake but i can't seem to figure out how to fix it. Help is appreciated!
function checklist(playlist){
for (var i = 0; i < playlist.length; i++){
var j = i+1;
document.getElementById("list").innerHTML += '<button id="removebtn'+j+'"></button>'
document.getElementById("removebtn"+j).addEventListener("click", function () {
delete playlist[i];
console.log("deleted");
});
};
}
I already tried: fixing problems with closure as described here: JavaScript closure inside loops – simple practical example
I also tried to work a way around by adding code programmatically: Adding code to a javascript function programmatically