Home > Net >  Putting a AddEventListener on a button that is in InnerHTML in a for loop
Putting a AddEventListener on a button that is in InnerHTML in a for loop

Time:04-16

Im am creating a page with some music, right now I am working on the 'explore' page. And you will see about 10 cards with music randomized from a array. Everything is going smoothly until right know. I added a button to start the music, but i can't seem to be able to put a AddEventListener on the button, i just made the cards with innerHTML (I know its not the best option but this project is still practice) And now I am not able to make it work on. If i put the event listener after the function with the innerHTML buttons. I am only able to get 1.

function handleLoadHighlights(number) {
    for (i = 0; i < 10; i  ) {
        let randomSongs = Math.floor(Math.random() * songsList.length);
        let song = songsList[randomSongs];
            let background = backgroundGradients[i];

            audioFile.src = song.audio;

            highlightsOutput.innerHTML  = `
            <div  style="${background.backgroundcolor} ${background.backgroundimg}">
                <div >
                    <h3 >${song.title}</h3>
                    <p >${song.artist}</p>
                </div>
                <div >
                    <button ><i ></i></button>
                    <img  src="./assets/covers/${song.img}"></img>
                </div>
            </div>
            `;
    }
}

The function that shows me the randomized card with the song

const playButton = document.querySelectorAll('.highlighted__button--play');

for(i = 0; i < 10; i  ) {
    playButton[i].addEventListener('click', handlePlayAudio);
}

My try on fixing it, just always returns the last one ofc

CodePudding user response:

Add the index of the song as a data attribute of the button.

function handleLoadHighlights(number) {
  for (i = 0; i < 10; i  ) {
    let randomSongs = Math.floor(Math.random() * songsList.length);
    let song = songsList[randomSongs];
    let background = backgroundGradients[i];

    audioFile.src = song.audio;

    highlightsOutput.innerHTML  = `
            <div  style="${background.backgroundcolor} ${background.backgroundimg}">
                <div >
                    <h3 >${song.title}</h3>
                    <p >${song.artist}</p>
                </div>
                <div >
                    <button  data-song="${randomSongs}"><i ></i></button>
                    <img  src="./assets/covers/${song.img}"></img>
                </div>
            </div>
            `;
  }
}

Then in handlePlayAudio(), you can get this index from the clicked button.

let songIndex = event.target.dataset.song;
audioFile.src = songsList[songIndex].src;

event is the argument to handlePlayAudio().

  • Related