Listening for events

  • Events are things that happen that Flash can recognize and respond to.
    • when sound completes
    • a frame is reached
    • a mouse event
    • a keyboard event
    • a timer finishes a countdown
  • Creating an event handler is a two part process
    • add a listener to detect the event and trigger a function
    • create a function that tells Flash how to respond
  • If you want to listen for a mouse click on a button you would write:
    • button1_btn.addEventListener(MouseEvent.MOUSE_OVER, buttonGrow);
  • The addEventListener() method takes two parameters.
      • the specific type of event you want to detect. (MouseEvent.CLICK)
      • the name of the function which is triggered when the event is triggered (buttonGrow)
  • In between the curly braces of the function you add actions as the response
    • button1_btn.addEventListener(MouseEvent.MOUSE_OVER, buttonGrow);
      function buttonGrow(event:MouseEvent):void{
               event.target.scaleX = event.target.scaleY = 1.1;
      }
  • When you no longer need to listen for an event you can delete the listener with the method removeEventListener(). The method takes two parameters identical to the ones in the addEventListener method.
MouseEvent Properties
CLICK Happens when the mouse button is clicked  
DOUBLE_CLICK Happens when the mouse button is clicked twice in rapid succession  
MOUSE_MOVE Happens when the mouse pointer is moved  
MOUSE_DOWN Happens when the mouse button is pressed  
MOUSE_UP Happens when the mouse button is released  
MOUSE_OVER Happens when the mouse moves from a non-targeted area to a targeted area  
MOUSE_OUT Happens when the mouse moves from a targeted area to a non-targeted area  
MOUSE_WHEEL Happens when the mouse wheel is rotated  
  • Try this to make an object play an animation on mouse over, play a different animation on mouse out, is draggable and the cursor changes over the object:
    • square.addEventListener(MouseEvent.MOUSE_DOWN, buttonDrag);
      square.addEventListener(MouseEvent.ROLL_OVER, buttonGrow);
      square.addEventListener(MouseEvent.MOUSE_OVER, customCursor);
      square.addEventListener(MouseEvent.MOUSE_OUT, cursorBack);
      square.addEventListener(MouseEvent.ROLL_OUT, buttonShrink);
      square.addEventListener(MouseEvent.MOUSE_UP, buttonStopDrag);
      function buttonDrag(event:MouseEvent):void{
      this.startDrag();
      }
      function buttonStopDrag(event:MouseEvent):void{
      this.stopDrag();
      }
      function buttonGrow(event:MouseEvent):void{
      event.target.gotoAndPlay(2);
      }
      function buttonShrink(event:MouseEvent):void{
      event.target.gotoAndPlay(16);
      }
      function customCursor(event:MouseEvent):void{
      Mouse.hide();
      cursor_mc.startDrag(true);
      cursor_mc.visible = true;
      }
      function cursorBack(event:MouseEvent):void{
      Mouse.show();
      cursor_mc.visible = false;
      }
< >