I have an array of songs, where each song has its index number in the array and the .source property. I wrote a script that creates a table row for each song:
var list = document.getElementsByClassName("preview")[1];
for (y = 0; y < allSongs.length; y ++) {
var row = list.insertRow(-1);
var celeft = row.insertCell(0);
var celright = row.insertCell(1);
celright.innerHTML = allSongs[y].name;
celeft.setAttribute("class", "left");
But now I want to make all those left cells (0) linked to the songs, which I tried to do this way:
x = document.getElementsByClassName("left");
var counter = 0;
while (counter < allSongs.length) {
x[counter+1].addEventListener('click', function() {
document.getElementById("audplayer").setAttribute("src", allSongs[counter].source);
});
counter++;
}
Basically, I made them clickable with the addEventListener property, but the problem is that the addEventListener function is not excecuted with the loop, so the counter value is not saved, and everytime I click one of the table cells, counter has a value of 3 at that moment. I understand where the problem comes from but I cannot solve it. How can this be solved?
More details (if the explanation wasnt clear enough): I want each of the table cells to perform a different action (play different songs), but they all play the same one - allSongs[3], because counter value is taken when the click event happens, not every time the while loop is executed.