O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Animating Straight-Line Element Paths

NN 6, IE 5

Problem

You want to animate the position of an element from one coordinate to another on the page along a straight-line path.

Solution

To animate a positioned element along a straight-line path, link the animeLine.js library (Example 13-2 in the Discussion) to your page and invoke the initSLAnime( ) function with at least the first five parameters in the following sequence:

  1. ID of the positioned element (as a string)

  2. x coordinate of the starting position

  3. y coordinate of the starting position

  4. x coordinate of the ending position

  5. y coordinate of the ending position

For example:

initSLAnime("floater", 100, 100, 400, 360);

Discussion

While you can move a positioned element along a hardwired straight-line path in far less code than shown in this recipe, the animeLine.js library shown in Example 13-2 provides a generalizable solution, in which you specify the ID of the element to move, the start and end coordinates, and the relative speed. The custom objects and functions perform all of the necessary math to accomplish the job, regardless of direction or length of travel.

Example 13-2. The animeLine.js library for straight-line animation

// animation object holds numerous properties related to motion var anime; // initialize default anime object function initAnime( ) { anime = {elemID:"", xCurr:0, yCurr:0, xTarg:0, yTarg:0, xStep:0, yStep:0, xDelta:0, yDelta:0, xTravel:0, yTravel:0, vel:1, pathLen:1, interval:null }; } // stuff animation object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required