Javascript eventhandler always being added to last object in array
Solution 1:
This is a classic 'pitfall' of JavaScript closures. Basically, your buttonParent
variable is being overwritten in every iteration and the anonymous function you're passing to addEventListener
references but does not copy this variable.
You'll probably need something similar to:
button.addEventListener('click', (function (parent) {
return function() {
toggleCollapsedPlugin(parent);
};
})(buttonParent), false);
For a more detailed explanation, see How do JavaScript closures work?.
In your case however, you can simply get rid of the closed variable altogether and find the button's parent when the anonymous function is called. This works because this
inside of the callback function refers to the element the event was registered on, being the element references by button
in that iteration.
button.addEventListener('click', function() {
return toggleCollapsedPlugin(this.parentNode.id);
}, false);
Solution 2:
You're declaring buttonParent, assigning it to the event call, but then changing it in the loop until eventually it refers to the last item.
I think all the events will point to this same reference.
Replace
button.addEventListener('click', function () { toggleCollapsedPlugin(buttonParent); }, false);
with
button.addEventListener('click', function () { toggleCollapsedPlugin(this.parentNode.Id); }, false);
"this" inside the event on the button object will be the button itself