Home / JavaScript
JavaScript animations with smalljs
tags: Animation smalljs
 
Let's explore smalljs.ui.js to perform basic element animations in JavaScript.

smalljs.UI
smalljs.UI is a small collection of UI related extensions and plugins for smalljs. For the examples in this post we will focus in the animate() method. The animate method is your typical setInterval() loop that gradually changes a value in the element in each iteration until it reaches the desired state.

sj().animate() and smalljs.ui.animate()
We can access the animate function either calling it directly from the literal object (smalljs.ui) or by passing an element reference, id, or name to the sj() object with the following parameters:
{
start:0,
end:100,
duration:2000,
onStep:function(i){},
callback:function(){}
animation:(ex. smalljs.ui.animations.exponential),
delay:10
}

The 'start' and 'end' parameters tell the function from which value to 'start' incrementing until it reaches the 'end'. The duration is used to calculate how long the animation will be (it can also be consider the speed of the animation). The parameter onStep expects the function that will be called during each iteration; the incremented value will be passed to this function as a parameter every time. The callback parameter expects a function that will be executed until the animation has reached its end. The animation parameter expects a function that will take the current progress value as a parameter and return a modify value to create different behaviors during the animation.

The default behavior of the animate function is a linear increment of the progress value:


If we introduce a function that will take the progress value and raise it to the n power we will end up with the following (this is what an animation function does):


Example:
Let's animate the div 'block' by changing its margin left from 0 to 500.

<script type="text/javascript">
smalljs.ready(function () {
sj('button').onClick(function () {

sj('block').animate({
start: 0,
end: 500,
onStep: function (tick) {
sj(this).get[0].style.marginLeft = tick + 'px';
}
});

});

});
</script>
<div>
<input name="button" type="button" value="start" />
<div>
<div id="block" style="width:50px;height:50px; background-color:orange;" >&nbsp;</div>
</div>
</div>



smalljs.ui.animations contains a collection of common pre-define animations to get you started.

The following example will add the exponential animation to the animate function.



sj('block').animate({
start: 0,
end: 500,
onStep: function (tick) {
sj(this).get[0].style.marginLeft = tick + 'px';
},
animation:smalljs.ui.animations.exponential
});


comments powered by Disqus