Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!