Spark - Animation

The development environment for the Spark animation function.

by Oliver Caldwell

HTML

<div id='target'></div>

CSS

div#target {
    background-color: #666666;
    width: 20px;
    height: 20px;
}

JavaScript

// Get the elements
var element = document.getElementById('target');

// Run the function
animate(element, {width: 10, height: 10}, 1000, function() {
    console.log('Done...');
});

// Create the function
function animate(element, properties, timeframe, callback) {
    // Set a default timeframe
    if(timeframe === undefined) timeframe = 800;
    alert(properties.length);
    // Loop through all properties
    for(var p in properties) {
        // Make sure the style is set
        element.style[p] = (window.getComputedStyle) ?
            window.getComputedStyle(element, null)[p] :
            element.currentStyle[p];
        
        // Get the original
        var original = parseInt(element.style[p]);
        
        // Work out the difference
        var difference = properties[p] - original;
        
        // Work out how many frames
        var frames = timeframe / (1000 / 60);
        
        // Work out how many pixels per frame
        var pixels = difference / frames;
        
        // Loop through each frame
        for(var i = 0; i <= frames; i++)
        {
            setTimeout((function(exti, element) {
                return function() {
                    element.style[p] = original + (pixels * exti) + 'px';
                }
            })(i, element), i * (1000 / 60), element);
        }

        // Correct floating point problem
        /*setTimeout((function(privateEye, elements) {
        return function() {
            elements[e].style.width = width + 'px';
            elements[e].style.height = height + 'px';
        }})(i, this.elements), timeframe, this.elements);*/
    }
    
    // Set callback timer
    if(callback !== undefined)
        setTimeout(callback, timeframe);
}