JoshG
JoshG

Reputation: 6735

Trouble changing audio source programmatically in JavaScript

I think I'm missing something silly. I'm creating a bunch of buttons with the title of an audio source. When a user clicks the button, the source should update in the audio player.

Unfortunately, the audio source always seems to be the last item. In other words, the buttons don't correspond to the correct source...they all just correspond to the same source.

Here is the code as I have it:

episodes = {0: {title: 'Audio 1', url: 'audio1.mp3'}, 1: {title: 'Audio 2', url: 'audio2.mp3'}, 2: {title: 'Audio 3', url: 'audio3.mp3'}};

for (var i = 0; i < Object.keys(episodes).length; i++) {
        var title = episodes[i].title;
    var url = episodes[i].url;
    var button = document.createElement('button');
    button.innerHTML = title;
    button.addEventListener("click", function() {
        $('#player').attr('src', url)[0];
        $('#player')[0].load();
    });
    document.body.appendChild(button);
}

Or, as a fiddle: https://jsfiddle.net/jmg157/1cL9p1qa/

In the fiddle, you'll notice that when you click on a button, the message in the console always shows the same value.

Any help would be greatly appreciated.

Upvotes: 0

Views: 50

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

Please try this:

episodes = {0: {title: 'Audio 1', url: 'audio1.mp3'}, 1: {title: 'Audio 2', url: 'audio2.mp3'}, 2: {title: 'Audio 3', url: 'audio3.mp3'}};

for (var i = 0; i < Object.keys(episodes).length; i++) {
        var title = episodes[i].title;
    var url = episodes[i].url;
    var button = document.createElement('button');
    button.innerHTML = title;
    button.audioUrl = url;
    button.addEventListener("click", function(e) {
        console.log(e.target.audioUrl);
        $('#player').attr('src', e.target.audioUrl)[0];
    });
    document.body.appendChild(button);
}

You must attach the url to the element because the variable url will retain the last value which is audio.mp3.

Demo: https://jsfiddle.net/y0mkw5gr/

Upvotes: 1

Related Questions