Using Timers in JavaScript - Sliding Around
(Page 6 of 7 )
Let's look at a couple more examples, which demonstrate just how useful - and varied - these functions can be. This first one uses the setInterval() method to create a timed slideshow:
<html>
<head>
<script language="JavaScript">
// slideshow image counter
var i = 0;
function slideShow()
{
// set up list of images
slidesArray = new Array()
slidesArray[0]="image1.jpg"
slidesArray[1]="image2.jpg"
slidesArray[2]="image3.jpg"
slidesArray[3]="image4.jpg"
slidesArray[4]="image5.jpg"
// load image
document.images[0].src=slidesArray[i]
// increment counter
i=i+1;
// when at the end, start again
if(i==5) { i=0; }
}
</script>
</head>
<body onLoad="javascript:setInterval('slideShow()',5000);">
<img src="image1.jpg" name="image">
</body>
</html>
Here, the images to be displayed are stored in a JavaScript array, and a "for" loop takes care of pulling out the correct image from the array and loading it into the page. The setInterval() method is used to refresh the image with a new one every 5 seconds.
You can also use the setInterval() method to move things around on a Web page, by incrementing an X- or Y-coordinate of a page element at a predefined interval. Consider the following example, which demonstrates by moving a <div> containing an image of a car across the screen.
<html>
<head>
<script language="JavaScript">
function moveCar()
{
if(document.all)
{
document.all("car").style.pixelLeft+=1;
if(document.all("car").style.pixelLeft >= (document.body.offsetWidth-30))
document.all("car").style.pixelLeft=-30;
}
if(document.layers)
{
parseInt(document.car.left+=5);
if(window.innerWidth-parseInt(document.car.left)<0)
document.car.left=-30;
}
}
</script>
</head>
<body onLoad="javascript:setInterval('moveCar()', 1)">
<!-- layer containing car image -->
<div id="car" style="position:absolute; left:20; top:200; width: 150;
height:50;">
<img src="rolls_royce.jpg" width=400 height=500 alt="" border="0">
</div>
</body>
</html>
Next: A Long Wait >>
More JavaScript Articles
More By Nariman K, (c) Melonfire