Crkva Kovacica Crkva Kovacica - 5 months ago 40
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

<a>
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>

Answer

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'));
});