Home > Software engineering >  How to execute a function on the right elements?
How to execute a function on the right elements?

Time:06-04

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  src="{{ $podcast.RelPermalink }}"></audio>

I have a button for each card to play audio :

<button >
    <img  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 ?

CodePudding user response:

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();
    }
  })
};
  • Related