Search code examples
javascriptbuttonaudiorandomplayback

Create button to play random sound files without using a variable? getElementsByTagName?


I want to add a button to play one of my soundfiles randomly. The problem is that I don't want to embed the audios in any variable, because this would be a lot of work to do.

Is it possible to maybe use "document.getElementsByTagName('audio')" to play the sounds?

BIG THANKS for your help.

cut from my html:


<a onClick="randomBtn()"></a>

<a class="buttonSB" onclick="document.getElementById('audiofile1').play();">
  <audio id="audiofile1" src="url/to/soundfile1.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile2').play();">
  <audio id="audiofile2" src="url/to/soundfile2.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile3').play();">
  <audio id="audiofile3" src="url/to/soundfile3.mp3"></audio>
</a> 
        




Solution

  • I hope it would work for you. I didn't check it.

    var s_files = document.getElementsByClassName('buttonSB')
      function randomBtn(){
        s_files[Math.floor(Math.random() * s_files.length)].click();
      }