Thought I would mix it up tonight before I moved onto Part 3 of creating a custom loop with pagination. I'm just going to post a quick way to have a custom image rotator that works accross all browsers, and can be used anywhere javascript can.
The main purpose to use a banner, or image rotator is for displaying ads. You can run out of room very quickly. I've noticed a few scripts out there that offer image rotation, but I never really liked how they worked. I figured that there was a better way to impliment a simple set of functions that would allow me to rotate through images (with links), that's not cholked down with unnecessary code.
So lets begin by setting up our images into our array. Create a new blank text document (call it quikchanger.js or something) and add the following:
var images=[ 'IMAGE OR LINK', 'IMAGE OR LINK', 'IMAGE OR LINK' ];
What we are doing is just setting up the images we will be providing for the rotator. Simple.
OK, so we have that down, lets set up our function that will grab our array of images (and/or links too) that we want to rotate, and make them rotate. Add the following directly AFTER (but on the same document) our script above:
function quikChanger( imgArray )
{
var quikMatches, lastImage, newImage, cookieSearch=/myImage=(\d+)/;if( typeof( document.cookie )!='undefined' && (quikMatches=document.cookie.match( cookieSearch )) && quikMatches.length>1 )
if( isNaN( lastImage=parseInt( quikMatches[1], 10) ) )
lastImage = -1;while( (newImage=Math.floor(Math.random() * imgArray.length)) == lastImage )
;document.cookie="myImage="+newImage;
return imgArray[ newImage ];
}
If you notice above we are using a cookie. This is to help the script not choose the same image. We also conduct some random math on the image, and return it back into our array.
Now we need to add our function that will make the image show up on our site:
document.write( quikChanger(images) );
We just simply use document.write() to display it. The best thing, you can add as many inages or links that you want to the code. Sweet! If you want to check out and example, refresh your browser and look for the change of the 125px x 125px banner in my sidebar...... Wow that was simple javascript!
the tags: image, javascript, js, rotate, rotator










1 Trackback or Pingback for this entry
August 18th, 2010 on 4:52 am
[...] Pełny artykuł na: Easy Javascript Image Rotator – Kris Jay Designs [...]