How to load a random image on pageload ~ Javascript

On my portfolio website I have an About page, where I explain… who I am of course! So I have a picture of myself in the sidebar, but got the idea that it’d be nice to have the picture change randomly on page load. I looked around at a few different options. Some were Javascript, some were PHP. It wasn’t worth turning the page into a PHP page just for this effect, so I went with Javascript. There are a lot of different options, but here’s the one I went with.
I made a div to surround the image, with the class of “me-box”. I gave this div a border, so the images will all appear to have a border when they are loaded. Next comes the Javascript code. This is where you give the src to your images. This code is put right in the body of your page where you want the images to appear, not in he head tag. A quick little piece of code that got the job done exactly like I wanted!
See the random image loading in action.
<div class=”me-box”>
<script language=”JavaScript”>
function banner() { } ; b = new banner() ; n = 0
b[n++]= “<img name=randimg src=’images/me.jpg’ >”
b[n++]= “<img name=randimg src=’images/me2.jpg’ >”
b[n++]= “<img name=randimg src=’images/me4.jpg’ >”
b[n++]= “<img name=randimg src=’images/me5.jpg’ >”
b[n++]= “<img name=randimg src=’images/me6.jpg’ >”
b[n++]= “<img name=randimg src=’images/me3.jpg’ >”
i=Math.floor(Math.random() * n) ;
document.write( b[i] )
</script>
</div>


October 22nd, 2009 at 7:24 am
Thanks.. this did exactly what I was looking for.
October 23rd, 2009 at 8:10 am
Great! Works exactly how it’s supposed to.
October 24th, 2009 at 12:28 pm
I can not get the script to work. I’ve tried just with using Dreamweaver and inside dreamweaver and I cant get to work. Also with Dreamweaver ID is used instead of class. Will the script with div -ID instead of using class for the div. If you know the problem and can shed light on this for me, it would be appreciated.
October 26th, 2009 at 4:19 am
It doesn’t matter if you are using Dreamweaver or not.. Just don’t use only the “design view”… you need to go into “code view”. You can use classes or id’s in Dreamweaver. Just copy the above code and paste it into the code view and it’ll work. Let me know if you have problems.
October 26th, 2009 at 10:05 am
I first tried this in Notepad before I even tried using it in Dreamweaver. For what ever reason I could get the images to show up. I got it working now, but fixed it in Notepad. Thanks for the script.
November 20th, 2009 at 3:47 am
I bet I know what the problem was. Sometimes when copying code over, you need to manually re-type in the quotes (” and ‘) marks.