Home › Forums › JavaScript › random img on page load
- This topic is empty.
-
AuthorPosts
-
February 19, 2009 at 7:53 pm #24202magicianMember
Iam desperately without success trying to get a different img to load up on each pageload/refresh:
here is mycode.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Future Mind Training | Life Coaching</title><link rel="stylesheet" type="text/css" href="css/styles.css">
<script type="text/javascript">
//<![CDATA[var images=new Array();
images[0]="photo1.jpg";
images[1]="photo2.jpg";
images[2]="photo3.jpg";ar i=Math.floor(Math.random()*images.length);
function randomImage() {
document.getElementById("random").src=Raw Images;
}onload=randomImage;
//]]>
</script>
</head><body>
<div id="wrapper"><!–included to allow for extension below main photos–>
<div id="container">
<div id="photo-frame"><img border="0" img id="random" src="Raw Images/photo1.jpg" width="800" height="544" >
</div><!–end of photo-frame–>
<!–navigation divs here–>
<div id="col1">
<h1 class="h1_welcome">welcome</h1>
</div><!–end of col1–></div><!–end of container–>
</div><!–end of wrapper–>
</body>
</html>what is wrong with it. it does not work.
February 20, 2009 at 12:21 am #53834Chris CoyierKeymasterOne thing I notice is that your original "src" starts with "Raw Images/", while the file paths in your JavaScript are just the image name. And.. when you set the .src in your randomImage function, you use "i", but "i" was declared outside of the function so it won’t know what that is. And.. that line should start "var" not "ar". And.. it should be " = images not Raw Images.
But anyway, I don’t think JavaScript is the right route for this. Why rely on a client side language when that could potentially be disabled?
Here is a really easy and "quick and dirty" way to do it with PHP:
February 21, 2009 at 5:24 am #53861ikthiusMemberI got a random image replacement script on one of my pages, uses php,
bear in ming I am just making the full image be squashed into the thumbnail area, I never resized to put a thumbnail in.
February 23, 2009 at 7:06 pm #54253davesgonebananasMemberI also agree that PHP is by far the best way to solve this problem. But supposing your host doesn’t provide PHP then you might want to try changing your randomImage function as follows:
Code:function randomImage() {
var i = Math.floor(Math.random()*images.length);
document.getElementById(“random”).src=”Raw Images/” + images[i];
}September 21, 2009 at 6:37 am #64503BeantownDesignParticipantHere’s a quick and easy way to load a random image on pageload with Javascript:
[url]
http://webdesignandsuch.com/2009/09/how … avascript/[/url] -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.