I'm trying to add event listeners to elements in a loop, but I'm struggling with getting the parameter to pass to the anonymous function correctly.
Here's an example of the html that I'm trying to apply the js to:
<button data-messagesend="Hello!">Send Hello</button>
<button data-messagesend="Goodbye!">Send Goodbye</button>
And here's the js:
// sendMsg function that will be applied to elements as an event listener
function sendMsg(msg) {
console.log(msg);
}
//Get all elements that have the data-sendmessage property
elts=document.querySelectorAll('[data-messagesend]');
//Create global array for messages
var messages=[];
//Loop through elements and add an event listener to call sendMsg with it's massage
for(i=0;i<elts.length;i++) {
//add element data-sendmessage value to messages array
messages[i]=elts[i].dataset.messagesend;
//add event listener
elts[i].addEventListener('click',function(){sendMsg(messages[i]);}.bind(messages[i]),false);
}
it's the //add event listener
line that I'm struggling with
I've also tried:
elts[i].addEventListener('click',function(){sendMsg(messages[i]);}.bind(messages,i),false);
and
elts[i].addEventListener('click',(function(msg){sendMsg(msg);})(messages[i]),false);
But it just returns undefined
when the buttons are clicked.
Any help would be great :D
Fiddle