I am busy writing a simple little animation library. The only thing I need is movement, so using something like jQuery or Zepto is going to be overkill. Plus, I want to use this to learn.
My Move function takes 4 parameters. x, y, interval and callback. It works fine but for 2 issues. The interval math is definitely out because it doesnt take the interval, and if the distance to move to is too close, it doesnt move at all.
Here is my code:
Move: function (x, y, interval, callback) {
interval = interval || 1000;
var that = this;
var elem = this._elem;
var dX = (x - parseInt(elem.style.left)) / (interval / 10);
var dY = (y - parseInt(elem.style.top)) / (interval / 10);
clearInterval(this.moveTimer);
this.moveTimer = setInterval(function () {
var cX = parseInt(elem.style.left);
var cY = parseInt(elem.style.top);
if (cY != y || cX != x) {
dX = Math.abs(dX) < Math.abs(x - cX) ? dX : (x - cX);
dY = Math.abs(dY) < Math.abs(y - cY) ? dY : (y - cY);
elem.style.top = (cY + dY) + "px";
elem.style.left = (cX + dX) + "px";
}
else {
clearInterval(that.moveTimer);
if (callback)
callback(that);
}
}, 10);
}
The issue is that when the x and y values are around 50px away, dX and dY become 0.
Note: dX and dY are the increment values for the relative axis. cX and cY are the current position.