Previous Page
Next Page

Recipe 9.23. Responding When Text Is Selected or Deselected

Problem

You want to perform a task when a text field is selected or deselected.

Solution

Listen for the focusIn and focusOut events.

Discussion

Text fields dispatch focusIn events when focus is shifted to the field and they dispatch focusOut events when focus is shifted away from the field. The events dispatched in both cases are flash.events.FocusEvent objects. The FocusEvent class defines a relatedObject property. In the case of focusIn events, the relatedObject property is a reference to the object that just had focus. In the case of focusOut events, the relatedObject property is a reference to the object that just received focus. Use the flash.events.FocusEvent constants of FOCUS_IN and FOCUS_OUT when registering listeners:

field.addEventListener(FocusEvent.FOCUS_IN, onFocus);

The focusIn and focusOut events both occur after the focus has already changed. They are non-cancelable events. If you want to be able to cancel the events, you must listen for events that occur before focusIn and focusOut are dispatched. The keyFocusChange and mouseFocusChange events are cancelable events that occur when the user attempts to move focus from a text field by way of the keyboard or mouse, respectively. You can register listeners by using the FocusEvent constants of KEY_FOCUS_CHANGE and MOUSE_FOCUS_CHANGE. Use the FocusEvent.preventDefault( ) method to cancel the default behavior. The following example disallows using the Tab key to move from field1 to field2 if field1 doesn't have any text:

package {

  import flash.display.Sprite;
  import flash.text.TextField;
  import flash.text.TextFieldType;
  import flash.events.FocusEvent;
  
  public class Text extends Sprite {

    private var _field1:TextField;
    private var _field2:TextField;

    public function Text(  ) {
      _field1 = new TextField(  );
      _field1.border = true;
      _field1.background = true;
      _field1.type = TextFieldType.INPUT;
      addChild(_field1);
      _field1.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, onKeyFocus);
      _field2 = new TextField(  );
      _field2.border = true;
      _field2.background = true;
      _field2.type = TextFieldType.INPUT;
      addChild(_field2);
      _field2.y = 100;
      
    }
    
    private function onKeyFocus(event:FocusEvent):void {
      if(_field1.text == "") {
          event.preventDefault(  );
      }
    }
    
  }
}


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)