Loading A Specific Image Sequence On Page Refresh Via JavaScript / DOM
Recently asked on Yahoo! Answers:
Anyone have a Javascript that will allow me to change an image on reload in order and not by random?
I basically need it to change an image when the user clicks reload. The image loaded I dont want to be on a randomizer. I found a code that will basically load a random image on reload. Here it is. I see where the randomizer is but I don’t know how to get it out:
[code snipped]
If I understand this question correctly, what this questioner wants to do is create an ordered list of images — Image 1, Image 2, Image 3, etc. — and display them, in order, with each page refresh.
This question is startlingly similar to the question I answered for displaying an image based on a schedule; in fact, we’ll use a similar approach here. But what this allows us to do is discuss how to use cookies in JavaScript — which is something new and fun.
As always, I’ll have a demo and code you can download at the end of the discussion.
Step 1: Write The XHTML
The Document Object Model end of this doesn’t get any simpler: All we need to do is create an IMG tag with a unique ID. We’ll ID our image as myImage. We also need to add an onload event to the BODY tag that will call our main function, which we call loadNextImage().
<body onload="loadNextImage();"> <img id="myImage" />
Step 2: The Cookie Functions
Because we want to show a new image on each page refresh — and because refreshing a Web page automatically destroys all JavaScript objects and variables on that page — we need a way to store the last image that was looked at, and to know which image we’re going to look at next.
That’s most easily accomplished with cookies: We store a small ID number on the user’s machine, and feed him an image based on that number. So, we need two functions: one that will set the value of the cookie, and another that will get the value of the image ID from the cookie.
Setting the cookie is simple. We’ll feed our function an integer; the function will then set a cookie, that expires in seven days, with a key-value pair for the image ID:
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
Getting the cookie’s value is only slightly more complicated.
- We set a return variable to have a default value of 0, then check to see if our cookie exists.
- If it does, we split the cookie into all the key-value pairs that are in the cookie; each key-value pair is delimited with a semicolon.
- We search the key-value pairs for the key imgID.
- Once we find that pair, we split the pair into an array around the = sign, then pop the final element — the value of imgID — off the array, and send it out as our return value.
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
Step 3: The Main Function
On to the main function. We first set a variable to refer to the IMG tag in our page; then we give the HTTP relative path to the directory in which we’ve stored our images.
Next, we declare an array that will contain all the names of the images we want to display, in the order we want them displayed. And then, we individually assign each image to a cell.
Note that you could easily replace this methodology with one that simply iterates through numbered images. I’m doing my script this way because it creates maximum flexibility for current Web sites.
function loadNextImage() {
//get image object
var myImg = document.getElementById('myImage');
//declare image directory path and image array
var thePath = "images/";
var theImages = new Array();
theImages[0] = "stacy_keibler_front1.jpg";
theImages[1] = "stacy_keibler_rear1.jpg";
theImages[2] = "stacy_keibler_front2.jpg";
theImages[3] = "stacy_keibler_rear2.jpg";
theImages[4] = "stacy_keibler_front3.jpg";
theImages[5] = "stacy_keibler_rear3.jpg";
theImages[6] = "stacy_keibler_front4.jpg";
theImages[7] = "stacy_keibler_rear4.jpg";
Next, we ask the getCookie() function to provide us with an integer that will provide the index of the array for the image to display. In other words, if getCookie() returns 0, we’ll display the image at index 0 of the array (in JavaScript, arrays always begin their index at 0).
We concatenate the directory in which our images are stored, along with the name of the image, to get its path; we then assign the source of our image to be that path, and the alt and title attributes to be the same as the name of the image.
//get current cookie value var currentIndex = parseInt(getCookie()); var imgPath = thePath + theImages[currentIndex]; myImg.src = imgPath; myImg.alt = theImages[currentIndex]; myImg.title = theImages[currentIndex];
Lastly, we need to increment the index stored in the cookie. To do that, we add 1 to the value we just got from the cookie, then see if the resulting value is more than the number of images we have to display.
If the number is too high, we reset our index to 0 and start iterating through the images anew. If the number is in range, we keep it.
Either way, we pass that value on to the setCookie() function.
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
And that’s all there is to it. You can see a working demo here:
http://www.dougv.com/demo/js_ordered_images_onload/
You can download the page and its images (thanks to Stuff Magazine for the images) here:
Loading A Specific Image Sequence On Page Refresh Via JavaScript / DOM Demo Code
I distribute code under the latest version of the Creative Commons Attribution / Share-Alike License.
















March 14th, 2007 13:08
[...] « Loading A Specific Image Sequence On Page Refresh Via JavaScript / DOM [...]
June 24th, 2008 10:17
Thanks for the code. Saved my time and energy.