Murphos
Murphos

Reputation: 25

Actionscript 3; how to make a toggle button?

Currently making a button that will toggle the visibility of a movie clip on and off. Here is my code;

infoButton.addEventListener(MouseEvent.CLICK, howToPlay);


var boxUp:Boolean = false;

function howToPlay(event:MouseEvent):void 
{
    if(boxUp == false)
    {
        infoBox.visible = true;
        boxUp = true;
    }
    if(boxUp == true){
        infoBox.visible = false;
        boxUp = false;
    }


}

However when clicking the button nothing happens. I'm assuming this is because it's a self contradicting function, however I don't know any other way to store if the movie clip is visible or not.

Can anyone help?

Upvotes: 0

Views: 1214

Answers (1)

null
null

Reputation: 5255

self contradicting function

Almost.

Step through the code with the debugger, you will see that both if statements are true. The first one enables the second one, which negates the effect of the first one.

Just do this:

function howToPlay(event:MouseEvent):void 
{
    infoBox.visible = !infoBox.visible;
}

but I'm really curious, as far as I can tell it's telling if the box is visible, then it's not visible?

Yes. The ! inverts a boolean value. The visible property is set to a value, which is its own value but inverted. If it's true, it becomes false and vice versa.

If using the property on both sides confuses you, try some simpler code first with hardcoded values:

    infoBox.visible = !true;
    infoBox.visible = !false;

Upvotes: 1

Related Questions