Click here to Skip to main content
15,844,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

JavaScript
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.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900