it's my first time asking question on Stack Overflow. Please excuse me for any mistakes.
I would like to know how I can change the first song played based on randomized ul. Currently, the list is being randomized each time I load the page, but the first song is always music/1.mp3. The following is my HTML and JS code:
HTML:
<audio id="audio" preload="auto" tabindex="0" controls="" >
<source src="music/1.mp3">
</audio>
<ul id="playlist">
<li>
<a href="music/1.mp3">
1
</a>
</li>
<li>
<a href="music/2.mp3">
2
</a>
</li>
<li>
<a href="music/3.mp3">
3
</a>
</li>
</ul>
JS:
var audio;
var playlist;
var tracks;
var current;
var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}
init();
function init(){
current = 0;
audio = $('#audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length;
audio[0].volume = 1;
audio[0].play();
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}