Search code examples
javascripttween

problem with simple tween class in javascript


I'm trying to build a simple Tween class in javascript. The code reads something like:

function Tween(object, parameters) {      // constructor-class def.
    this.object = object;
    this.parameters = parameters;
    this.isRunning = true;
    this.frameRate = some value;
    this.timeElapsed = some value;
    this.duration = some value;
}

Tween.prototype.drawFrame = function () {
    var self = this;
    this.nextFrame();
    if (this.isRunning)
        setTimeout( function () { self.drawFrame() } , 1000 / frameRate);
}

Tween.prototype.nextFrame = function () {
    if (this.timeElapsed < this.duration) {
                // calculate and update the parameters of the object
    } else
        this.isRunning = false;
}

Tween.prototype.start = function () {
    this.isRunning = true;
    this.drawFrame();
}

This is then called by another script, say main.js :

window.onload = init;

init = function() {

var tweenDiv = document.createElement('div');
tweenDiv.id = 'someDiv';
document.body.appendChild(tweenDiv);
var myTween = new Tween(document.getElementById('someDiv').style, 'left', parameters);
myTween.start();

}

Unfortunately, this doesnt work. If I examine my site with Google Chrome developer tools, someDiv has its left-style-attribute set to the number of pixels set in the parameters. But it doesn't move on the screen.

Anybody know what I'm doing wrong? Why isn't someDiv being redrawn?

Much Obliged


Solution

  • You have to set the position style to absolute, fixed or relative for the left style to have any effect.