Copy link to clipboard
Copied
Hello
I was wondering if it's possible to add multiple buttons to an event listener with a for loop? I have looked for similar solutions but don't think I quite understand them...
Essentially I have a number of buttons with consecutive instance names (e.g. but1, but2, but3 etc.) and want to assign them all to the same event listener. Something like:
for (i=1; i<5; i++) {
this.but[i].addEventListener("click", fl_MouseClickHandler.bind(this));
}
I have two arrays lined up to match this numbering and it would be great if I could return the entries from those arrays once the relevant button is clicked on also. Something like:
function fl_MouseClickHandler(e)
{
for(i = 1; i < 5; i++){
if(e.currentTarget.name == but[i]){
var myVal = this.myArray[i]; //pull my array values
}
}
Hope that makes sense!
Thanks
}
Hi.
In bracket notation, the dynamic property is a string. So your first code should be like this:
for (i = 1; i < 5; i++) {
this["but" + i].addEventListener("click", fl_MouseClickHandler.bind(this));
}
I hope it helps.
Regards,
JC
Copy link to clipboard
Copied
Hi.
In bracket notation, the dynamic property is a string. So your first code should be like this:
for (i = 1; i < 5; i++) {
this["but" + i].addEventListener("click", fl_MouseClickHandler.bind(this));
}
I hope it helps.
Regards,
JC
Copy link to clipboard
Copied
If I have several buttons I make an array and use forEach() but I know others have different ways of doing it. This is for Animate HTML5/CANVAS.
// code in frame 1
var root = this;
function useButtons(button, t) {
button.addEventListener("click", answerQuestion.bind(this));
function answerQuestion() {
// your code here
}
}
[root.Btn1, root.Btn2, root.Btn3, root.Btn4, root.Btn5].forEach(useButtons);
Copy link to clipboard
Copied
Thanks very much to both of you. Working lovely now and much appreciated 😀