I would like to use a div element as a button that, when clicked, plays a random audio file from a selection of files.
The threads here and here address random audio selection. From those sources, I came up with this script, which uses Math.random:
<script>
var xaudio = [ "link1", "link2", "link3"];
var randomxaudio = Math.floor(Math.random()*xaudio.length);
function playx() {
var audio = 'document.getElementById("clickx").innerHTML="<audio src=\""+randomxaudio+"\"/>"';
audio.play();
}
</script>
And this HTML:
<div class="button1" onclick="playx()" id="clickx">
<audio id="randomxaudio">
</audio>
</div>
This returns nothing on click. As I'm quite new to the whole programming thing, I don't understand JS well enough to identify what could be wrong (or right) about this approach, and I can't seem to get anything I find online to work for me. Any advice would be much appreciated.