Tuesday, July 14, 2015

Resetting CSS3 Transitions and Animations

Everyone gets excited whenever they get the opportunity to work with CSS3 and particularly the new transition and animation features. They work smoothly compared to Javascript animations, and the reason they do is because these visual interactions are managed by the browser itself and how it decides to interpret the movement of elements that it has rendered from markup. This is significantly more efficient than how Javascript tries manipulating DOM elements functionally by altering the rendered elements frame by frame.

With every great thing however, there are always shortfalls. Lets look specifically at animations and their keyframes.

.notify {
    animation: notify 5s;
@keyframes notify {
    from { height: 0; }
    20% { height: 60px; }
    80% { height: 60px; }
    to { height: 0; }

This is a very simple implementation of a keyframe animation to slide an element down for notifications. All that is needed is a div element that initially doesn't have a "notify" class.

<div id="tip" class="tip">message</div>

With a little Javascript we can add the "notify" class to the element so that the keyframe can be triggered. We can do this with JQuery.


There is one problem with this however. Once this keyframe has been executed, it can no longer be executed unless you refresh the page.

One way which should typically solve this problem would be to remove the class then re-add it again.


That would be logical, unfortunately it doesn't work!
Amazingly, what is required is to set any property of the element, even if it is to the same value.


$(".tip").position().top = $(".tip").position().top;


The reason for this is it helps trigger a "reflow" of the browser so as to listen for the next time the "notify" class has been added to the element, and the browser will do its magic all over again!

No comments :