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

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

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