Copy link to clipboard
Copied
Hi everyone,
I place 10 buttons on my stage, name it "b1", "b2", "b3",.. , "b10".
All these buttons should use the same function.
Is it possible to do it dynamically?
var a: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0; i < a.length; i++) {
button = "b" + a;
this[button].addEventListener(MouseEvent.CLICK, onClick_b);
function onClick_b(pEvt: Event): void {
my_mc.play();
}
}
Only the button "b10" plays the function.
Anyone an idea how to let all the other buttons play this function?
Thank you! C.
what you want is this:
for (var i = 0; i < a.length; i++) {
getChildByName("b" + a).addEventListener(MouseEvent.CLICK, onClick_b);
}
Copy link to clipboard
Copied
Assuming all your buttons are Button symbols, and hence are SimpleButtons and they all exist at the point you run this code:
var loops:numChildren;
for (var i:int=0; i<loops; i++) {
var btn:SimpleButton = getChildAt(i) as SimpleButton;
if (btn) {
btn.buttonMode = true;
btn.addEventListener(MouseEvent.CLICK, onButtonClick);
}
}
//note the function is defined outside the for loop
function onButtonClick(e:Event):void {
if (my_mc) {
my_mc.play();
}
}
Copy link to clipboard
Copied
Thank you for your answers, this solution works, but I need an array in my project...
Now my buttons are called "bone", "btwo", "three".
var button: String;
button = "b";
var a: Array = ["one","two","three"];
for (var i = 0; i < a.length; i++) {
button = "b" + a;
button.addEventListener(MouseEvent.CLICK, onClick_b);
}
function onClick_b(pEvt: Event): void {
my_mc.play();
}
But it doesn't work...
Copy link to clipboard
Copied
var button: String;
...
button.addEventListener(MouseEvent.CLICK, onClick_b);
You can`t add en eventlistener to a string
Copy link to clipboard
Copied
Hi mm, I tried this:
this[button].addEventListener(MouseEvent.CLICK, onClick_b);
and it works for the button "bthree".
But the other buttons won't work.
Copy link to clipboard
Copied
what you want is this:
for (var i = 0; i < a.length; i++) {
getChildByName("b" + a).addEventListener(MouseEvent.CLICK, onClick_b);
}
Find more inspiration, events, and resources on the new Adobe Community
Explore Now