Crkva Kovacica Crkva Kovacica - 10 months ago 81
Javascript Question

How to make a mp3 player play songs when i click on them from my <a> tag?

I made a list of songs in my

tags, and I want the mp3 player to be universal for every song, so when i click on one song(link) from the list it would be played on the player, and it wouldn't have to refresh the page, or open it in another tab to play the song?

Here is my HTML:

<audio preload="auto" src="#"></audio>

<a class="trigger" href="#" data-src="audio/song1.mp3">Song #1</a>
<a class="trigger" href="#" data-src="audio/song2.mp3">Song #2</a>
<a class="trigger" href="#" data-src="audio/song3.mp3">Song #3</a>
<a class="trigger" href="#" data-src="audio/song4.mp3">Song #4</a>


Since you tagged the question with jQuery, you can simply use that to set the src attribute of your audio element. Something like this:

$('a').on('click', function () {
    $('audio').prop('src', $(this).data('src'));