Javascript Image Rotator

0

Posted on : 04-10-2008 | By : Stefan | In : Javascript

Ever wanted to rotate through a bunch of images easily without having to use *cough* Flash? Well now you can by using the few lines of code below and a bit of JS (Javascript) trickery.

First we need to include the javascript files in to our webpage by putting the following 2 lines in to the <head>

<script src=”js/dw_rotator.js” type=”text/javascript”></script>
<script src=”js/dw_event.js” type=”text/javascript”></script>

<script type=”text/javascript”>
// Add rollover events
var rotator1 = {
path:   ‘badges/’,
id:   ‘rotateImg’,
speed:  3000,
images: ["audi.jpg", "bmw.jpg", "ford.jpg", "logo.gif", "honda.gif", "landrover.jpg", "mazda.jpg", "mercedes.jpg", "logo.gif", "mini.jpg", "peugeot.jpg", "renault.jpg", "saab.jpg", "logo.gif", "skoda.jpg", "vauxhall.jpg", "vw.jpg"],
bTrans: true // ie win filter
}

function initRotator() {
dw_Rotator.setup(rotator1);
}

addLoadEvent(initRotator);

</script>
</head>

dw_event.js – The events to trigger the automatic scroller.
dw_rotator.js – The code which does the js image trickery.
var rotator1 – The image path, id (of the <img> coming next), rotate speed, and lastly the image array.

You can add as many images into the array as you want, just be aware of loading times on slower browsers.

Next we add the image into our web site. I prefer to wrap the image into a <div> to make it easier to move around and manage. As you can see the ID is “rotateImg” as specified in var rotator1. This means you could have for example var rotator2… name the id rotateImg2 and set the id of your next image to rotateImg2, thus giving you another rotating image block without too much hassle.

<div id=”div-1″><img id=”rotateImg” src=”img/logo.gif” alt=”Logo”></div>

Download dw_rotator.js (Thanks to Sharon Paine & Dynamic Drive)
Download dw_event.js
View demo

Post a comment