Skip to content

Declarative animations

chemerisuk edited this page Nov 3, 2014 · 1 revision

In better-dom animation capabilities are CSS-driven. It means that your animations should be described in CSS. And the role of JavaScript APIs is to trigger and to connect events in your application logic with the animation events.

In CSS3 we have 2 modules: transitions and animations. Both cover specific use cases.

In all code examples below the -webkit- prefix won't be included, but you have to add it for each property in real code. Or just use autoprefixer that can handle it for you.

Using CSS3 transitions

Transitions are useful when you need to animate a change of a specific property (or several properties).

To animate a visibility change you need to specify 2 states: normal and hidden. For a hidden state use standards-based aria-hidden attribute like below:

.foo {
    opacity: 1;

    transition: opacity 1s;
}

.foo[aria-hidden=true] {
    opacity: 0;
}

Now to trigger a fade animation use a simple call:

var foo = DOM.find(".foo");

foo.hide(); // element fades out

Notice that the library does not remove element from the flow. You should do it by yourself (if needed). The easiest method is to do it when animation is done:

foo.hide(function() {
    // remove element from the flow when animation is completed
    foo.css("position", "absolute");
});

Now you can fade in the element back using show:

// restore element in the flow and trigger animation
foo.css("position", "").show(); 

In general try to use CSS3 transitions if possible, because they are easier to undestand although do not have such flexibility as CSS3 animations.

Using CSS3 animations

CSS3 animations provide a wider capabilities for user interaction. On the other hand they are a bit more complex.

Visibility methods in better-dom (e.g. hide, show, toggle) accept keyframes name as the first optional argument.

Let's redo fade animation using CSS3 animations.

@keyframes fading {
    from { opacity: 1 }
    to   { opacity: 0 }
}

Now you need to specify animation property on a target element:

.foo {
    animation: none 1s;
}

Notice, that we use none as animation name, because the animation-name property will be set inline during the call:

foo.hide("fading", function() {
    // remove element from the flow if your need
});

Then we can trigger fade in animation:

foo.show("fading"); 

For a hidden element better-dom automatically sets animation-direction: reverse, therefore hide and show animations are different.

Fallback for old browsers

Library detects old browsers and just uses display: none to hide element and to remove it from the flow.