May 30, 2000 - Implementing Quaking Windows | WebReference

May 30, 2000 - Implementing Quaking Windows

Yehuda Shiran May 30, 2000
Implementing Quaking Windows
Tips: May 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Another way to grab your visitors' attention is to make your window quaking and shaking. Click the following button to start the quake:

If quakes make you feel sick, click the following button to stop:

The jump() method returns a random integer from -maxShift to maxShift. The following code segment is responsible for a single quake:

for (var i = 0; i < (minJumps + (Math.random() * (maxJumps - minJumps))); i++) {
  dX = jump();
  dY = jump();
  window.moveBy(dX, dY);
  totalX -= dX;
  totalY -= dY;

Since we have no way of knowing the window's initial position, we must keep track of how much we moved it in each direction. The totalX and totalY variables hold the window's position in relation to its initial position, before the quake began. When the quake is over, the window is moved back to its origianl position:

window.moveBy(totalX, totalY);
totalX = 0;
totalY = 0;

The winShake() function is then called again after a random pause:

quakeID = setTimeout("winShake()", Math.ceil(Math.random() *
  (maxBetweenQuakes - minBetweenQuakes)) + minBetweenQuakes);

The script generates a series of earthquakes. It begins when the page loads (window.onload).

See the full script in Tutorial 1, Working with Windows.