Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button class="tocar_audio" data-alvo="exemplo_a">Tocar Audio A</button>
  <button class="tocar_audio" data-alvo="exemplo_b">Tocar Audio B</button>
  <audio id="exemplo_a" controls>
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mp3">
  </audio>
  <audio id="exemplo_b" controls>
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3" type="audio/mp3">
  </audio>
</body>
</html>
 
var variavelGlobal = null;
document.querySelectorAll('.tocar_audio').forEach(function (e) {
  e.addEventListener('click', tocarAudio, false);
});
function tocarAudio(e) {
  var alvo = (e.target).dataset.alvo;
  if (variavelGlobal) {
    document.getElementById(variavelGlobal).pause();
    document.getElementById(variavelGlobal).currentTime = 0;
  }
  document.getElementById(alvo).play();
  variavelGlobal = alvo;
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers