214-564-5316
Thursday, May 17, 2012

Dynamic animation: fly in and shake screen

Refresh the page to see it again.
View source for code.

The trigger for any javascript (like the fly in animation and the screen shake code which uses the moveBy() function) has to be "onSomething" like onClick, onLoad, onUnload, etc. This is called the "event handler".  We'll set the javascript functions to be triggered when the page finishes loading (the body onLoad statement). The trick is to get the page shaking javascript to be timed correctly. When using more than one event in the event handler the browser loads the last one first. So, lets say your function to shake the page is called "shake(n)" where n is the length of time the page shakes. The body tag that loads the dynamic FP fly in function and the shake function might look like this:
<body onload="shake(1);dynAnimation()">
So far so good? Nope. Even though both functions are called correctly (and the animation is in the correct spot to be handled first) the screen will shake first and THEN the image flies in. (Because it takes a bit of time for the javascript to load and the image to fly-in).  So to correct this we write a simple function that sets up a timer like this:
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- Begin
function timedAlert()
{
var the_timeout = setTimeout("shake(1);",550);
}
// End -->
</script>

This simply tells the browser to wait 550 milliseconds after page load before running the function "shake(1)"
(note: 1000 milliseconds=1 second)
To make this work we change the body tag to read:
<body onload="timedAlert();dynAnimation()">
Now the dynamic animation flies in and 550 milliseconds later the page shakes.