Animated Floating Sidebar

I wrote this the other day and thought it was worth posting here. It is Javascript that will allow you to float a div that moves up and down as the user scrolls the webpage in the browser window. It will speed up and animate faster if the user scrolls quickly from spot to spot or slower if they scroll slowly.

Here is the Javascript.

<script type="text/javascript">
/**
 * Animates a floated div to move up and down with the scrolling of the page.
 *
 * More details at http://www.finefrog.com/2007/12/14/animated-floating-sidebar/
 *
 * @author Jordon Mears <jordoncm at gmail dot com>
 */
function animate_box() {
    var offset = 0; /* set this to the starting margin-top in the css */
    var element = document.getElementById('animate_box');

    if(element) {
        var top = Number(String(element.style.marginTop).substring(0, String(element.style.marginTop).indexOf('px')));

        var difference = (document.documentElement.scrollTop + offset) - top;

        if(difference > 0) {
            element.style.marginTop = (top + Math.abs(Math.ceil(difference / 10))) + 'px';
        } else if(difference < 0) {
            element.style.marginTop = (top - Math.abs(Math.ceil(difference / 10))) + 'px';
        }
    }
}
window.setInterval(animate_box, 50);
</script>

Here is the div. Since it is just a float, you can easily embed it inside other elements.

<div id="animate_box" style="float: right;">I am an animated div that scrolls with the browser window.</div>

Click here to see an example of it at work.

It works in all standard compliant browsers and Internet Explorer 6+ (maybe even older).

You are welcome to use this for whatever you want; I just ask that you retain the credits (and maybe leave me a comment).

Leave a Reply

{
}