user3794271
user3794271

Reputation: 3

Randomized music play via HTML javascript not working correctly

What I'm trying to do is randomly generating background embed on each page load from 0-3 as shown below. This file is located in body section of index.html.

<script type="text/javascript">
var music = [],
index = 0;

music[0] = "<embed name="myMusic" loop="false" hidden="true" src="music1.mp3"></embed>";
music[1] = "<embed name="myMusic" loop="false" hidden="true" src="music2.mp3"></embed>";
music[2] = "<embed name="myMusic" loop="false" hidden="true" src="music3.mp3"></embed>";
music[3] = "<embed name="myMusic" loop="false" hidden="true" src="music4.mp3"></embed>";

index = Math.floor(Math.random() * music.length);
document.write(music[index]);
</script>

The issue is that the music does not play in any browser with the above script.

Upvotes: 0

Views: 93

Answers (1)

user2226755
user2226755

Reputation: 13173

Add slash before double quote like this :

music[0] = "<embed name=\"myMusic\" loop=\"false\" hidden=\"true\" src=\"music1.mp3\"></embed>";

Or replace double quote like this :

music[0] = '<embed name="myMusic" loop="false" hidden="true" src="music1.mp3"></embed>';

Full code :

<script type="text/javascript">
var music = [],
index = 0;

music[0] = '<embed name="myMusic" loop="false" hidden="true" src="music1.mp3"></embed>';
music[1] = '<embed name="myMusic" loop="false" hidden="true" src="music2.mp3"></embed>';
music[2] = '<embed name="myMusic" loop="false" hidden="true" src="music3.mp3"></embed>';
music[3] = '<embed name="myMusic" loop="false" hidden="true" src="music4.mp3"></embed>';

index = Math.floor(Math.random() * music.length);
document.write(music[index]);
</script>

Upvotes: 1

Related Questions