1

I'm trying to use .addEventListener inside a loop with arrays (if that's at all possible) for use with multiple audio players on the same webpage. The audio players are just standard HTML5 audio but with custom controls.

This is just some test code to explain:

array[0].addEventListener('click',function() {
    array[0].play();
});

array[1].addEventListener('click',function() {
    array[1].play();
});

How would I be able to condense rather than writing this out for every value of the array? I've already tried putting it inside a (for) loop but then it just appeared to ignore it altogether:

For (i = 0; i < array.length; i++) {
    array[i].addEventListener('click',function() {
        array[i].play();
    });
}

Apologies in advance if I'm being an idiot and/or missing something obvious.

3
  • 2
    for loop would be a correct way to do it, however, you have a scope problem. Every click handler bound within the loop will call .play() on the last item in the array. Commented Jun 3, 2014 at 14:05
  • you should try using closures.. Commented Jun 3, 2014 at 14:07
  • No problem. I rolled back your edit because it isn't relevant to the question, please keep comments in the... comments section. :) Commented Jun 3, 2014 at 14:35

1 Answer 1

0

try to use this code

for( var i=0; i<array.length; i++ )
{
    (function(index)    // keep i pointing to right index
    {
        array[index].addEventListener('click', function ()
        {
            array[index].play();
        }, false);
    })(i)

}

PS: I am no ninja in closures so if it doesn't work. Apologies

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

4 Comments

don't return, it exits the loop on the first iteration. You are somewhat close though, you need to remove the return, turn the function declaration into a function expression, then execute it. (function(i){...})(i)
something like that? @KevinB
Yes, but your first ( is backwards, and you need to use index inside, not i. and... play isn't defined, that needs to be an anonymous function
edit it for me please..@KevinB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.