Transition effects in JavaScript can be divided into two groups: movement effects and fading effects. Movement effects look smoother when acceleration and deceleration are used to prevent the animation starting and stopping abruptly. SmoothMovement is a JavaScript object that aids the creation of such transition effects. In the example below, SmoothMovement is used in two ways: to slide between the planets and to change their size. Both transitions can occur at the same time, and the target planet can be changed while a slide is in progress.
















Download SmoothMovement
Download one of the files below and upload it to your web server.
File | Size | Description |
---|---|---|
SmoothMovement.js | 4,775 bytes | Full version, with comments |
SmoothMovement.compressed.js | 1,472 bytes | Compressed version |
Link to the file using a script element in the head of your page:
1 |
|
Using SmoothMovement
When creating an instance of SmoothMovement, two parameters may be specified. The first parameter, which defaults to 0, sets the position — the value used to produce movement. The second parameter, which defaults to the same value as the position, sets the target — the value that the position will smoothly change to. For example:
1 2 3 4 5 6 7 8 |
|
The position and target can be accessed and changed at any time using the position and target properties:
1 2 |
|
The update function updates the position, smoothly moving it towards the target. As a convenience, it returns the new position:
1 2 |
|
The hasStopped function returns whether the movement has permanently stopped (and hence whether future calls to the update function will return the same value):
1 2 3 4 5 6 |
|
Animating with SmoothMovement
The animate function aids the creation of animations using SmoothMovement. It calls the update function and a user-supplied function at regular intervals, and can call a second user-supplied function when the animation has finished.
The animate function takes up to three parameters. The first parameter is the interval, in milliseconds, between updates. The second parameter is a function to call after each update. This function will be passed the position and the SmoothMovement instance as parameters. The optional third parameter is a function to call when the animation has finished. This function will be passed the SmoothMovement instance as a parameter.
As an example, the following code collapses an element with the ID ‘help’ by smoothly reducing its height (lines 11 to 13) and finally hiding it (lines 14 to 16).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|