Multiple Buttons Sharing One Function (passing a button ID to a function)

Explorer ,
Aug 07, 2021 Aug 07, 2021

Copy link to clipboard

Copied

Attempting my first Animate project with a background in ActionScript and D3-flavored interactive SVGs but otherwise no web development experience.

 

I need several buttons to call the same function, and I need the function to know which button called it. In ActionScript and D3 I would have put code on the button passing the button ID, or a portion of it, to the function – something like this, with "changestate" being the function and "this.id" being the button name or ID:

onmouseup="changestate(this.id.substring(0,3))"

 

But in Animate it seems we have to use event listeners in place of code attached to buttons. I haven't been able to figure out how to pass any info from the button to the function via the listener; as far as I can tell listeners don't seem to be designed to do that. I could create a separate function for each of the six buttons, but I'd rather the code be more economical and elegant than that. What's the solution?

TOPICS
Code , How to

Views

29

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Aug 07, 2021 Aug 07, 2021

Copy link to clipboard

Copied

LATEST

use the currentTarget of the event passed to your listener function. and you can add properties to your button to give whatever identifying info is needed in the listener function. eg,

 

for(var i=0;i<11;i++){

this["button"+i].id = "btn_"+i;

this["button"+i].addEventListener("click",f.bind(this));  // binding not needed here, but good habit to use.

}

function f(e){

console.log(e.currentTarget.id);

}

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines