A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: optimize script to do similar activity for various buttons

  1. #1
    Junior Member
    Join Date
    Mar 2007

    Thumbs up optimize script to do similar activity for various buttons


    Iam having 3 buttons in stage and three corresponding movieclips. When I clicked on one button, it should play its corresponding movieclip from the second frame. (Same case for the rest of the buttons)

    Here the action for the three buttons are almost same, only the movieclip differs. In AS2, I can optimize the script for the above activity as below

    for (var i = 1; i<=3; i++) {
    _root["btn_"+i].onRelease = function() {
    myname = this._name.split("_")[1];

    In AS3, I can able to write the equivalent script as below,

    btn_1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    btn_2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    btn_3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    function mouseDownHandler(event:MouseEvent):void {
    var nam = event.target.name;
    var mcaction = nam.split("_")[1];
    this["mc_" + mcaction].gotoAndPlay(2);


    My Question is ===>

    is there any way to add the Event listeners for all the 3 buttons using "for loop" instead of initializing it for each buttons seperately ?

    [Imagine if we have more than 10 buttons and it will be very boring to add the listener for each button in a seperate line ].

    Thanks in Advance for your responses

  2. #2
    Ө_ө sleepy mod
    Join Date
    Mar 2003
    Oregon, USA
    PHP Code:
    var btns:Array = [btn_1btn_2btn_3];

    each(var b:MovieClip in btns){

  3. #3
    Junior Member
    Join Date
    Mar 2007
    Hey Great!


    Since I have used the button, I modified your suggestion a little bit to match my requirement.

    for each (var b:SimpleButton in btns) {
    b.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width

HTML5 Development Center