Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

Disabling an Actionscript SimpleButton

by Jim Mar 13, 2007 5:12 PM

According to the AS3 Language Reference, the enabled property of a SimpleButton is supposed to prevent the button from being clicked, as one might expect. Only it doesn't - the CLICK event is still fired when the button is disabled.

The trick is to set the SimpleButton's hitTestState property to null in order to disable the button. The hit test state is used to test whether the mouse is over the button; if it's null, the test will always fail and the button can't respond to click events - really.

If your button is derived from SimpleButton, this is simple to do in an override of the enabled property:

public override function set enabled(value:Boolean):void
{
 super.enabled = value;
 createStates();  // Redraw the states so they show as disabled
}

// Redraw each of the states
protected function createStates():void
{
 if (enabled)
 {
  upState = createState([0xDDDDDD, 0xC9C9C9, 0xCCCCCC, 0xAAAAAA]);
  overState = createState([0xFFFFFF, 0xFAFAFA, 0xDDDDDD, 0xCCCCCC]);
  downState = createState([0xFFFFFF, 0xDDDDDD, 0xCCCCCC, 0xAAAAAA]);
  hitTestState = upState;
 }
 else
 {
  // Only the upState is going to show in this case, since mouse is ignored
  upState = createState([0xFFFFFF, 0xFAFAFA, 0xF0F0F0, 0xDCDCDC]);

  // This is what flash test against to see whether to fire a click event; setting the 
  // hit test state to null is how we *really* disable a button
  hitTestState == null;
 }
}