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

84
Views
How to toggle multiple play/pause buttons with different srcs

I'm facing some issues with my play/pause buttons. In ym HTMl I have multiple buttons with different sources:

<div>
 <button class="button-53" id="button">Play</button>
</div>

<audio id="player">
  <source src='audio/mixdown.mp3' type='audio/mpeg'/>
</audio>

<div>
 <button class="button-53" id="button">Play</button>
</div>

<audio id="player">
  <source src='audio/mixdown2.mp3' type='audio/mpeg'/>
</audio>

This is my Javascript:

var buttons = document.getElementById("button");
var music = document.getElementById("player");

for (const buttons of button) {
buttons.addEventListener("click", function(){
  if(music.paused){
    music.play();
    buttons.innerHTML = "Pause";
  } else {
    music.pause();
    buttons.innerHTML = "Play";
  }

});
}

But when I play music from the first button and then pause it, go over to the next button and toggle the button, the sound keeps playing from that point where I stopped it instead of playing the sound from the written source.

Anyone here that could help me?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Id attributes in HTML should be unique. The document.getElementById returns a single element (if found).

One solution to fixing your problem is to give each pair of button/audio elements different ids, for example:

<div>
 <button class="button-53" id="button1">Play</button>
</div>

<audio id="player1">
  <source src='audio/mixdown.mp3' type='audio/mpeg'/>
</audio>

<div>
 <button class="button-53" id="button2">Play</button>
</div>

<audio id="player2">
  <source src='audio/mixdown2.mp3' type='audio/mpeg'/>
</audio>

and then add event listeners for each pair:

function addListeners(buttonElement, audioElement) {
    // ...add implementation
}

addListeners(
    document.getElementById("button1"),
    document.getElementById("player1")
);
addListeners(
    document.getElementById("button2"),
    document.getElementById("player2")
);
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!