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

202
Vistas
How to execute a function on the right elements?

I am templating a HUGO website with a list page with cards. I have audio files from content in each card. Here are the html elements :

<audio class="podcast__audio" src="{{ $podcast.RelPermalink }}"></audio>

I have a button for each card to play audio :

<button class="podcast__player_button">
    <img class="podcast__player_play" src="/images/podcast/play.png">
</button>

In Javascript I play audio with this function :

const podcastAudio = document.querySelector('.podcast__audio');

function toggleAudio () {
  if (podcastAudio.paused) {
    podcastAudio.play();

  } else {
    podcastAudio.pause();
  }
}

I display 4 cards on the list page and each card has one different audio file to play.

I have a for loop for the event listener on the buttons :

const podcastPlayerButton = document.querySelectorAll('.podcast__player_button');

for (let i = 0; i < podcastPlayerButton.length; i++) {
  podcastPlayerButton[i].addEventListener('click', toggleAudio);
}

It works fine but it toggles only the first audio file of the page (which makes sense) but I want it to play the audio file linked to each card. The first podcast__player_button button should play the first podcast__audio file, the second button should play the second audio file and so on.

I guess I need to querySelectorAll audio files and iterate on it ? How to execute the toggleAudio() function on the right audio files ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Ok because buttons and audio files have the same index this code works :

for (let i = 0; i < podcastPlayerButton.length; i++) {
  podcastPlayerButton[i].addEventListener('click', function () {
    if (podcastAudio[i].paused) {
      podcastAudio[i].play();
    } else {
      podcastAudio[i].pause();
    }
  })
};
about 4 years ago · Juan Pablo Isaza 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