user3245340
user3245340

Reputation: 3

Change song using jquery and <audio>

I've been trying to create a webpage that plays several different songs when the user clicks a button. I've been using the value attribute on buttons to store what the name of the song to send to the audio player. When the button is clicked the song stays as the default, any help would be appreciated!

HTML

<button value="newsong.mp3">NEW SONG</button>
<audio controls id="player" src="sound/default.mp3" autoplay></audio>

Javascript

var song;
$(document).ready(function(){
  $("button").click(function(){
    song=$(this).attr("value");
    $("#player").attr("src","sound/"+song);
    });
  };
});

Edit: switched names on accident copying code; both ids are player not music

Upvotes: 0

Views: 1445

Answers (2)

Zword
Zword

Reputation: 6787

You are using an extra }; in your JS code:

var song;
$(document).ready(function(){
  $("button").click(function(){
    song=$(this).attr("value");
    $("#player").attr("src","sound/"+song);
  });
});

See this Fiddle

Upvotes: 1

weaknespase
weaknespase

Reputation: 1034

Audio tag has id music and you try to change attribute on tag with id player. Since there is no such tag, song will not change.

Upvotes: 0

Related Questions