Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
Putting a AddEventListener on a button that is in InnerHTML in a for loop

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 class="highlighted__song" style="${background.backgroundcolor} ${background.backgroundimg}">
                <div class="highlighted__description">
                    <h3 class="highlighted__description--title">${song.title}</h3>
                    <p class="highlighted__description--para">${song.artist}</p>
                </div>
                <div class="highlighted__footer">
                    <button class="highlighted__button--play"><i class="fas fa-play-circle"></i></button>
                    <img class="highlighted__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

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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 class="highlighted__song" style="${background.backgroundcolor} ${background.backgroundimg}">
                <div class="highlighted__description">
                    <h3 class="highlighted__description--title">${song.title}</h3>
                    <p class="highlighted__description--para">${song.artist}</p>
                </div>
                <div class="highlighted__footer">
                    <button class="highlighted__button--play" data-song="${randomSongs}"><i class="fas fa-play-circle"></i></button>
                    <img class="highlighted__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().

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda