-1

I put the following JS directly on a site of my WordPress blog. It should play one of the two audio files randomly if you click on a button.

My question is:

  • Is there anything wrong / missing with the JS
  • How can I get it started by a button?
<script>
var playlist = Array();
playlist.push("http://.../wp-content/uploads/2015/03/xxx.mp3");
playlist.push("...wp-content/uploads/2015/03/10-Good-Evening.mp3");


console.log(getSong()); // Here's your song.

document.getElementById("play").addEventListener("click", playSong);


function playSong(){ 
    var audio = new Audio(getSong());
    audio.play(); 
}

function getSong() {
   return playlist[Math.floor(Math.random() * playlist.length)];
} 

</script>
paule
  • 9
  • 3

2 Answers2

1

looks good!

just add this html after your javascript tag

<button id="play">Click Me</button>
Sol Garger
  • 21
  • 2
  • Thanks for helping me. I did this but it still doesn't work. You can see it here: http://fuba-blog.de/randomizer/ – paule Mar 19 '15 at 19:25
1

The console shows:

Navigated to http://fuba-blog.de/randomizer/
VM83:132 Uncaught SyntaxError: Unexpected token <

Navigating to the error shows

     <script>
var playlist = Array();
playlist.push("http://fuba-blog.de/wp-content/uploads/2015/03/alaba-button-mp3.mp3");
playlist.push("http://fuba-blog.de/wp-content/uploads/2015/03/alaba-button-mp3.mp3");</p>
<p>console.log(getSong()); // Here's your song.</p>
<p>document.getElementById("play").addEventListener("click", playSong);</p>
<p>function playSong(){ 
    var audio = new Audio(getSong());
    audio.play(); 
}</p>
<p>function getSong() {
   return playlist[Math.floor(Math.random() * playlist.length)];
} </p>
<p></script>

You have HTML in your script.

epascarello
  • 204,599
  • 20
  • 195
  • 236