O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing an Item from the Display List

Problem

You want to remove an item from the display list and consequently remove it from the screen.

Solution

Use the removeChild() and removeChildAt() methods from the DisplayObectContainer class.

Discussion

Recipe 6.1 demonstrates how to add display objects to the display list using the addChild() and addChildAt() methods. To achieve the opposite effect and remove a child via one of these methods, use either the removeChild() or removeChildAt() method.

The removeChild() method takes a single parameter, which is a reference to the display object that should be removed from the container. If an object is supposed to be removed and it isn’t a child of the container, an ArgumentError is thrown:

package {
  import flash.display.Sprite;
  import flash.text.TextField;
  import flash.events.MouseEvent;

  public class RemoveChildExample extends Sprite {
    
    // Create a local variable to store a reference
    // to the TextField so that we can remove it later
    private var _label:TextField;
    
    public function RemoveChildExample() {
      _label = new TextField();
      _label.text = "Some Text";
      
      // Add the hello TextField to the display list
      addChild( _label );
      
      // When the mouse is clicked anywhere on the stage,
      // remove the label
      stage.addEventListener( MouseEvent.CLICK, removeLabel );
    }
    
    // Removes the label from this container's display list
    public function removeLabel( event:MouseEvent ):void {
      removeChild( _label );
    }
  }
}

The preceding code example creates a local variable label ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required