Category Archives: Operators

Toggle .visible

Actionscript:
  1. // toggle a DisplayObject's visible property
  2. var shape = new Shape();
  3.  
  4. shape.visible = !shape.visible;
  5. trace(shape.visible); // outputs false
  6.  
  7. shape.visible = !shape.visible;
  8. trace(shape.visible); // outputs true
  9.  
  10. shape.visible = !shape.visible;
  11. trace(shape.visible); // outputs false
  12.  
  13. shape.visible = !shape.visible;
  14. 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:

Actionscript:
  1. var circle:Shape =  new Shape();
  2. circle.graphics.beginFill(0xFF0000);
  3. circle.graphics.drawCircle(0, 0,10);
  4. circle.x = 80;
  5. circle.y = 105;
  6. addChild(circle)
  7.  
  8. var btn:TextField = new TextField();
  9. btn.text = "click this text to toggle red circle's visibility";
  10. btn.x = btn.y = 100;
  11. btn.selectable = false;
  12. btn.border = true;
  13. btn.autoSize = TextFieldAutoSize.LEFT;
  14. addChild(btn);
  15.  
  16. btn.addEventListener(MouseEvent.CLICK, onClick);
  17. function onClick(evt:MouseEvent):void{
  18.     circle.visible = !circle.visible;
  19. }

Because "not false" is true.

Posted in Operators | Leave a comment