Skip to main content
Participant
March 15, 2021
Answered

Ad multiple Buttons to event listener

  • March 15, 2021
  • 3 replies
  • 425 views

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

}



    This topic has been closed for replies.
    Correct answer JoãoCésar17023019

    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

    3 replies

    Participant
    March 15, 2021

    Thanks very much to both of you. Working lovely now and much appreciated 😀

    avid_body16B8
    Legend
    March 15, 2021

    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);

     

    JoãoCésar17023019
    Community Expert
    JoãoCésar17023019Community ExpertCorrect answer
    Community Expert
    March 15, 2021

    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