[Solved] Javascript click event in for loop not working?


Looks like you want to be able to hide other albumCover elements on clicking one of them.

There are a couple of mistakes

  • Your inner for-loop re-localize the scope of i, use different variable
  • i’s value (assuming another variable is used in inner for-loop) will not remain same when the click will happen.

Make it

function albumCoverDisplay() 
{
  for (let i = 0; i < albumCover.length; i++)  //use let instead of var
  { 
    albumCover[i].addEventListener("click", function() {
      for (var j = 0; j < albumCover.length; j++) 
      {
          albumInfo[j].style.display = "none";
      }
      albumInfo[i].style.display = "block";
    });
  }
}

1

solved Javascript click event in for loop not working?