Animating an element’s visibility using AngularJS

There was a question on StackOverflow about animating an element and I wanted to give it a shot, so here goes:

http://jsfiddle.net/wiredprairie/5tFCZ/1/

image

 

Imagine nearly the simplest Angular JS application possible:

<div ng-app="App">
    <div ng-init="checked=true">
        <div>
            <label>
                <input type="checkbox" ng-model="checked" />Is Visible...</label>
        </div>
        <div class="sample" ng-class="{ hidden: !checked }">Visible...</div>
    </div>
</div>

There is only a single property called checked as part of the data model. There’s a checkbox that when unchecked, will cause the text “Visible” to be hidden.

I’m going to use jQuery as the simple animation engine, but you could use what ever you’d like. The latest versions of jQuery, angular, and angular-animate are needed:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.10/angular-animate.min.js"></script>

Using the ng-class directive (reference), a CSS class named hidden is added when the checkbox is not checked.

The application module and animation API are defined:

angular.module('App', ['ngAnimate']).animation('.sample', function () {
    return {
        addClass: function (element, className, done) {
            if (className === 'hidden') {
                jQuery(element)
                    .css({
                    opacity: 1
                })
                    .animate({
                    opacity: 0
                }, 500, done);
            } else {
                done();
            }
        },
        removeClass: function (element, className, done) {
            if (className === 'hidden') {
                jQuery(element)
                    .css({
                    opacity: 0
                })
                    .animate({
                    opacity: 1
                }, 500, done);
            } else {
                done();
            }
        }
    }
});

 

The only element animated on the page is using a CSS class name of sample. Whenever Angular adds or removes a CSS class from a matching HTML element, the corresponding code is executed. As it’s possible for multiple class names to be passed to the functions, per the guidelines, I’ve made sure that the code only executes when appropriate by filtering on the class name of hidden. As it’s toggling the state, the first action taken is to fully make opaque or transparent, then animate to zero or one depending on whether the class is being added or removed.

And that’s it! Of course, the code could have been more sophisticated, but it was all I needed.

By the way, there’s no need for a CSS class named hidden that has any CSS properties (it can be undefined completely). The animation code handles the visibility properly.