1. Home
  2. Computing & Technology
  3. JavaScript
This is a web page object.
hide

Web Page Animation

6. Now You See It

clr gif

So far we have hidde an object until the page finished loading and then displayed it on the page for a set period of time (or until our visitor clicks on a link). In this tutorial we will look at having the object appear and disappear at set intervals until our visitor clicks on the hide link. First we need to amend the processing of the hide link to call a function.

<div id="myobj">
This is a web page object.<br /><a href="#"
onclick="stopAnim();return false;"
>hide</a></div>

Next we replace the setTimeout function call within the 'start' function (which performed the call to hide the object after two minutes) with a setInterval call that will toggle the visibility of the object every two seconds. We also need to assign it to a global variable (defined outside of the function) so that we will be able to turn off the processing from inside another function. As before, the rest of our existing code remains unchanged so I wont show it here.

var animat = null;
function start() {
var w = objWidth('myobj');
var h = objHeight('myobj');
xxx = Math.floor(Math.random()* (pageWidth()-w));
yyy = Math.floor(Math.random()* (pageHeight()-h));
moveit();
setObjVis('myobj','visible');
animat = setInterval("toggleObjVis('myobj')",2000);
}

Finally we need to add our 'stopanim' function that is called from the hide link.

function stopAnim() {
clearInterval(animat);
setObjVis('myobj','hidden');
}

Unlike setTimeout which is runs the called function once after the specified time has passed, setInterval runs the specified function (in this instance toggleObjVis from our object function library) continuously waiting the specified amount of time between one run and the next. This contstant calling of the function is only cancelled by the clearInterval call that we have added in front of the call that hides the object for the final time. of course our visitor will only be able to click on the hide link that is in the object itself during the half of the time that the object is visible. You may prefer to move the link onto the page itself so that the hide link is always available.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.