Experimenting with the element.animate() function

Here’s a short blog post with two simple demos that I’ve created when playing around with the new element.animate() function that was included in Chrome 36, a function which makes it possible to create CSS animations using JavaScript.

Please note that this isn’t a tutorial and the demos might contain errors since they are created in experimental purpose.

As a comparison, the first demo is created strictly using CSS animations and in the second demo I’ve used the element.animate() function.

Demo One, CSS Version

HTML

<p>Hover over the box ...</p>

<div id="box"></div>

CSS

html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
text-align: center;
background: #eee;
}

p {
font: lighter 24px "Helvetica Neue", sans-serif;
color: #222;
letter-spacing: 2px;
}

#box {
position: absolute;
left: 0;
top: 20px;
bottom: 0;
right: 0;
margin: auto;
width: 75px;
height: 75px;
border-radius: 15px;
border: 1px solid #222;
}

#box:hover {
-webkit-animation: rotate 2s linear 2 ;
animation: rotate 2s linear 2;
}

@-webkit-keyframes rotate {
0%   {-webkit-transform:rotate(0deg) scale(1.0);transform:rotate(0deg) scale(1.0);}
50%  {-webkit-transform:rotate(180deg) scale(1.4);transform:rotate(180deg) scale(1.4);}
100% {-webkit-transform:rotate(360deg) scale(1.0);transform:rotate(360deg) scale(1.0);}
}

@keyframes rotate {
0%   {transform:rotate(0deg) scale(1.0);}
50%  {transform:rotate(180deg) scale(1.4);}
100% {transform:rotate(360deg) scale(1.0);}
}

Demo Two, JS Version

Requires Chrome 36+ to work.

HTML

<p>Hover over the box ...</p>

<div id="box"></div>

CSS

html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
text-align: center;
background: #eee;
}

p {
font: lighter 24px "Helvetica Neue", sans-serif;
color: #222;
letter-spacing: 2px;
}

#box {
position: absolute;
left: 0;
top: 20px;
bottom: 0;
right: 0;
margin: auto;
width: 75px;
height: 75px;
border-radius: 15px;
border: 1px solid #222;
}

JS

(function () {

var box = document.getElementById('box');

box.onmouseover = function () {

box.animate([{
transform: 'rotate(0deg)' + 'scale(1.0)'
}, {
transform: 'rotate(180deg)' + 'scale(1.4)'
}, {
transform: 'rotate(360deg)' + 'scale(1.0)'
}

], {
duration: 2000,
iterations: 2

});

};

})();

As you can see both demos are more or less working the same, except that the animation in the CSS version will break (stop) on mouse out.

For more detailed information regarding the element.animate() function, please visit html5rocks.com or https://developer.mozilla.org

2 Replies to “Experimenting with the element.animate() function”

Leave a Reply