I’ve got some code which creates an < audio > element and plays a song, when I click on a button. So far so good. The button turns from “Play Music” into “Stop Music” as it’s clicked.
Now I added this code:
audioElement.addEventListener('ended', function() {
$('span#pause').fadeOut('slow');
$('span#play').delay(1500).fadeIn('slow');
});
Which technically should show the Play-Button again, when the song is over. But it doesn’t. Could anybody tell my why?
Here’s the whole code:
$(document).ready(function() {
var songList = [
'song1.ogg',
'song2.ogg',
'song3.ogg'
];
var randomNumber = Math.floor(Math.random()*songList.length);
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', songList[randomNumber]);
audioElement.load();
audioElement.addEventListener('ended', function() {
$('span#pause').fadeOut('slow');
$('span#play').delay(1500).fadeIn('slow');
});
$('#play').click(function() {
audioElement.play();
$('span#play').fadeOut('slow');
$('span#pause').delay(1500).fadeIn('slow');
});
$('#pause').click(function() {
audioElement.pause();
$('span#pause').fadeOut('slow');
$('span#play').delay(1500).fadeIn('slow');
});
});
The answer to your question in your comment to start the next song: change the
src-attribute of theaudiotag. E.g. add a newbuttoncalled “next” and following script:Also see the updated jsfiddle.
=== UPDATE ===
randonNumberwill be incremented. The modulo%(remainder of division) prevents, that the number is higher then the number of songs.audiotag will be set to the next song.clickevent will be triggered, like somebody had clicked on theplay button, so theplay click handlerstarts the song and changes thebuttonvisibility.