Browse the notebook

Category: Operators

Toggle .visible

// toggle a DisplayObject's visible property
var shape = new Shape();

shape.visible = !shape.visible;
trace(shape.visible); // outputs false

shape.visible = !shape.visible;
trace(shape.visible); // outputs true

shape.visible = !shape.visible;
trace(shape.visible); // outputs false

shape.visible = !shape.visible;
trace(shape.visible);  // outputs true

This is pretty obvious to anyone with a full understanding of the ! operator. It’s useful for things
like checkboxes and other types of toggle buttons. The first time I ever encountered this technique
was in processing source… in one of the demos on toxi.co.uk

Here’s another quick example you can run in your timeline:

var circle:Shape =  new Shape();
circle.graphics.beginFill(0xFF0000);
circle.graphics.drawCircle(0, 0,10);
circle.x = 80;
circle.y = 105;
addChild(circle)

var btn:TextField = new TextField();
btn.text = "click this text to toggle red circle's visibility";
btn.x = btn.y = 100;
btn.selectable = false;
btn.border = true;
btn.autoSize = TextFieldAutoSize.LEFT;
addChild(btn);

btn.addEventListener(MouseEvent.CLICK, onClick);
function onClick(evt:MouseEvent):void{
	circle.visible = !circle.visible;
}

Because “not false” is true.

Read snippet: Toggle .visible