requestAnimationFrame hello world

by Richard Hunter

HTML

<div id="foo"></div>

CSS

#foo {
    position : absolute;
    top : 100px;
    width : 100px;
    height : 100px;
    background : red;
}

JavaScript

function Foo(el) {

    this.el = $(el);
    this.left = 0;
    this.direction = "ltr";
}

Foo.prototype = {

    move: function () {

        if (this.direction === 'ltr') {
            this.el.css({
                left: this.left++
            });
            if (this.left > 300) {
                this.direction = 'rtl';
            }
        } else {
            this.el.css({
                left: this.left--
            });
            if (this.left < 0) {
                this.direction = 'ltr';
            }
        }
    }
}

var foo = new Foo(document.querySelector('#foo'));

(function animloop() {
    window.requestAnimationFrame(animloop);
    foo.move();
})();