Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda