Krillen
Krillen

Reputation: 1

Trying to use basic Javascript to animate a div and make it bigger but have it grow smoothly

so here's my code

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    #box {
        width: 300px;
        height: 300px;
        background-color: blue;
    }
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script src="main.js"></script>
</html>

javascript

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

function changeColor() {
    box.style.width = "600px";
    box.style.height = "600px";
    box.style.background = "red";
}

box.onclick = setInterval(changeColor, 5000);

As you can see it changes in a flash. I have the box changing size and color but what i want it to do it gradually. I know its easy in Jquery but I'm trying to further my skills in Javascript, any advice would help, thanks guys and gals.

Upvotes: 0

Views: 2127

Answers (1)

David Barker
David Barker

Reputation: 14620

The basic premise behind javascript animation is recursion. The animating element needs to have 'frames', a single frame requires a timeout until it's next sequence, this is why recursion is beneficial.

Note: This function will not stop animating the div, you will need to put conditional code in to stop the setTimeout() being set.

function moveEl(el)
{
    var left = parseInt(el.style.left) || 0;

    el.style.position = 'relative';
    el.style.left = (left + 1) + 'px';

    // Recursive timeout to move the element left 1px every 20ms
    setTimeout(function(){
        moveEl(el);
    }, 20);
}

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

// Start the animation
moveEl(el);

jsFiddle Example

This should get you on the way to writing some custom animation code, though I would treat this very much as a learning exercise. jQuery's animation techniques are very powerful, cross browser compatible and are imo much more useful than any custom code I would cobble together to achieve the same effects.

Animating between colours:

To animate smoothly between the colours is a little trickier as you would, if using the above technique, require a load of hex colour codes between the two colours to smoothly transition from one to the other. Fortunately in modern browsers you can animate the opacity of one element down to zero whilst the solid colour of the element beneath appears as if one element has animated. Again jQuery has a number of ways to support IE7 and IE8 etc with its fadeIn() and fadeOut() functions.

Upvotes: 2

Related Questions