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

203
Visualizações
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 Respostas
Responde à pergunta

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 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