Reputation: 45
I'm trying to program a playlist for a site I'm presently working on, and I'm having some issues presently. I've written the script so far and it replaces the default song with a second song, but does not revert back on click.. any suggestions?
The HTML...
<audio id="player" src="../audio/small-skeletal.mp3" type="audio/mp3" controls autoplay></audio>
<div id="audio_list" style="margin-top: 100px;">
<div id="track">
<h2 class="change-song" data-track="http://www.birp.fm/music/playlists/2014/january-2014/027%20-%20Phantogram%20-%20Fall%20In%20Love.mp3">Switch to second song</h2>
<h2 id="bb" class="change-song" data-track="http://www.logicwebmedia.com/dev/ecb/new-dev/audio/small-skeletal.mp3">Change it back!!</h2>
</div>
$('.change-song').click(function(){
var song = $('.change-song').data('track');
$('#player').attr('src', song).attr('autoload', 'auto').attr('autoplay');
});
The script only ever returns the first song as the value, and never the second.. how do I fix this?
Upvotes: 0
Views: 366
Reputation: 26877
Change your $('.change-song').data('track');
to $(this).data('track');
which will give you correct scope. Sorry for changing song files in the snippet.
$('.change-song').click(function() {
var song = $(this).data('track');
$('#player').attr('src', song).attr('autoload', 'auto').attr('autoplay');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttonmit2ani">
<audio id="player" src="audio/acdc.ogg" controls autoplay></audio>
<div id="audio_list" style="margin-top: 100px;">
<div id="track">
<h2 id="aa" class="change-song" data-track="audio/acdc.ogg">Switch to second song</h2>
<h2 id="bb" class="change-song" data-track="audio/radiohead.ogg">Change it back!!</h2>
</div>
</div>
</div>
Upvotes: 0
Reputation: 337560
You need to use this
as a reference to the clicked .change-song
element in the click handler. Your current code is selecting both elements at once and when you retrieve the track
data attribute it only gets it from the first element in the matched set.
$('.change-song').click(function(){
var song = $(this).data('track');
$('#player').attr('src', song).attr('autoload','auto');
});
Upvotes: 1
Reputation: 6097
Change your click
function to:
$('.change-song').click(function(){
var song = $( this ).data('track');
$('#player').attr('src', song).attr('autoload','auto').attr('autoplay');
});
this
is a reference to the element that was clicked.
Upvotes: 5