Skip to main content
Inspiring
November 25, 2018
Answered

Use the same function for many buttons

  • November 25, 2018
  • 1 reply
  • 429 views

Hi,

I want to use the same function for each of my buttons instances. I will need to have about 90 buttons that will use the same function and each function will need to send parameter to another SWF.

Here is the basic code. How would you make it in the way to use the same function for the two buttons? Thank you.

buttonF1.addEventListener(MouseEvent.CLICK,btnpressed1);

buttonF2.addEventListener(MouseEvent.CLICK,btnpressed2);

function btnpressed1(e:MouseEvent){

    buttonF1.removeEventListener(MouseEvent.CLICK,btnpressed1);

buttonF1.enabled = false;

buttonF1.visible = false;

}

function btnpressed2(e:MouseEvent){

    buttonF2.removeEventListener(MouseEvent.CLICK,btnpressed2);

buttonF2.enabled = false;

buttonF2.visible = false;

}

This topic has been closed for replies.
Correct answer Robert Mc Dowell

just do

buttonF1.addEventListener(MouseEvent.CLICK,btnpressed); 

buttonF2.addEventListener(MouseEvent.CLICK,btnpressed);

function btnpressed(e:MousEvent):void{

     e.target.removeListener(MouseEvent.CLICK,btnpressed);

     e.target.enabled = false;

     e.target.visible = false;

}

1 reply

Robert Mc Dowell
Robert Mc DowellCorrect answer
Legend
November 25, 2018

just do

buttonF1.addEventListener(MouseEvent.CLICK,btnpressed); 

buttonF2.addEventListener(MouseEvent.CLICK,btnpressed);

function btnpressed(e:MousEvent):void{

     e.target.removeListener(MouseEvent.CLICK,btnpressed);

     e.target.enabled = false;

     e.target.visible = false;

}

KoRnBoy82Author
Inspiring
November 25, 2018

Thanks, corrected it a little to make it work. Now, since each buttons has a number, how can I make it send an argument corresponding to the button number that will be used by another external SWF loaded each time to display some text?

buttonF1.addEventListener(MouseEvent.CLICK,btnpressed);

buttonF2.addEventListener(MouseEvent.CLICK,btnpressed);

function btnpressed(e:MouseEvent):void{

     e.target.removeEventListener(MouseEvent.CLICK,btnpressed);

     e.target.enabled = false;

     e.target.visible = false;

}

Ned Murphy
Legend
November 26, 2018

If you utilize the name property of the event target it will identify the button that was clicked...  e.target.name

You should be able to deal with breaking down the string if need be... or name the buttons to more directly reflect the parameter you wish to process.

If you want to be sure to get the button and not some object within it, use currentTarget instead.  That points to the object that has the event listener assigned to it.