Bidirectional Animation With Booleans

December 21, 2018

I came across a piece of code I wrote for a project several months ago, and it struck me as being a little creative, so I thought I’d share it with a short explanation.

In this Angular project, I have a menu button component that, when clicked, shows or hides an attached menu using a scale transform applied via GreenSock tween. Pretty simple, right? My standard approach when implementing a custom toggle button is typically to have a property behind the scenes storing the button’s state as a boolean. Then, I check that boolean on click to determine which state I am toggling to, and fork the logic accordingly. Typically, there would be separate animations for showing and hiding, and that boolean check would determine which one to use.

In a lot of cases, this is as simple as it gets. But in my case, I’m using a scale transform, changing scale from 0 to 1 or from 1 to 0. (It would be the same if I was using opacity instead of scale.) Changing a value back and forth between 0 and 1 is a numeric representation of a boolean: false is 0, true is 1. And in JavaScript, these values can be easily coerced between types, which means I actually have to set up only one animation.

public isMenuOpen: boolean;

public toggleMenu(): void {
	this.isMenuOpen = !this.isMenuOpen;
	TweenMax.to(this.menu.elem, 1, { scale: +this.isMenuOpen });
}

View source on GitHub

My boolean tracking the state of the menu can actually pull double-duty as the value of the scale. When the menu is closed, the property is false and the scale is 0. When the menu is open, the property is true and the scale is 1. In other words, when the menu is at rest, the property double-equals (not triple-equals) the scale. So, when I need to change the state, I’m flipping that boolean, setting it to the opposite of what it currently is. And putting the plus sign before the variable name in JavaScript coerces the value to a number; in the case of a boolean, false becomes 0 and true becomes 1.

Again, this won’t work in a lot of cases because the logic and/or animation behind the state change is just more complicated than flipping a boolean and has more moving pieces. But in the cases that are simple enough to use it, it’s a pretty handy shortcut.


Philip Fulgham is a software engineer who builds web applications. Visit this website's front page to learn more.