0

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.

2
  • are you sure you have 0,1,2 as key in the episode? Commented Jul 2, 2016 at 6:17
  • 1
    I think this is a closure problem. For example url is overwritten with every iteration so all your buttons will load audio3.mp3. Check the related section of this answer and you will find some guidance to your problem. Commented Jul 2, 2016 at 6:47

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm and the explanation really helps! Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.