0

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.

SHC MostWanted
  • 101
  • 1
  • 7

1 Answers1

0

Try replacing your loops with map and _.zip from lodash.

Example pseudocode:

song_and_elem_pairs = _.zip(allSongs, x);
song_and_elem_pairs.map(function (song, elem) {
    elem.addEventListener('click', function() {
        document.getElementById("audplayer").setAttribute("src", 
            song.source);
    }
});

You can also similarly replace the for (y = 0; y < allSongs.length; y ++) loop with a map.

This is certainly not the only way to do this, but it's how I would approach it and I think it should fix your problem.

anandsun
  • 186
  • 6
  • The foreach strategy in the link Yury posted above might be simpler if you're more familiar with loop comprehensions than higher order functions. – anandsun Jul 18 '17 at 13:31