Jump to content

Random background image...


Jonas

Recommended Posts

I'm making a website, where I need to be able to switch background image randomly for each load. Can anyone help me with this? I know I have to create an array of variables, but I don't know how to write the actual code.

Link to comment
Share on other sites

here is what I find in javascript.internet.com , and change a little :)

<!-- TWO STEPS TO INSTALL RANDOM BACKGROUND:   1.  Add the designated script to the HEAD of your HTML document   2.  Place the last script into the BODY of your HTML document  -->    <!-- STEP ONE:  Add this script to the HEAD of your HTML document  --><HEAD><script LANGUAGE="JavaScript"><!-- This script and many more are available free online at --><!-- The JavaScript Source!! [url="http://javascript.internet.com"]http://javascript.internet.com[/url] --><!-- Beginfunction backcolor(form) {temp = ""for (var i = 0; i < 16; i++) {temp = form.color[i].valueif (form.color[i].checked){ document.bgColor = temp }   }}function randombackground() {document.bgColor = getColor()}function getColor(){currentdate = new Date()backgroundcolor = currentdate.getSeconds()if (backgroundcolor > 44)backgroundcolor = backgroundcolor - 45else if (backgroundcolor > 29)backgroundcolor = backgroundcolor - 30else if (backgroundcolor > 15)backgroundcolor = backgroundcolor - 16if (backgroundcolor == 0 )return "olive";else if (backgroundcolor == 1 )return "teal";else if (backgroundcolor == 2 )return "red";else if (backgroundcolor == 3 )return "blue";else if (backgroundcolor == 4 )return "maroon";else if (backgroundcolor == 5 )return "navy";else if (backgroundcolor == 6 )return "lime";else if (backgroundcolor == 7 )return "fuschia";else if (backgroundcolor == 8 )return "green";else if (backgroundcolor == 9 )return "purple";else if (backgroundcolor == 10 )return "gray";else if (backgroundcolor == 11 )return "yellow";else if (backgroundcolor == 12 )return "aqua";else if (backgroundcolor == 13 )return "black";else if (backgroundcolor == 14 )return "white";else if (backgroundcolor == 15 )return "silver";}// End --></SCRIPT><!-- STEP TWO:  Put this form in the BODY of the HTML document  --><BODY onload="randombackground()"></body>

Link to comment
Share on other sites

Yeah, I found that same script, but I need images, not background-colors. And I don't know how to change that script. Also, to make it valid and still work, all I need to change is language="javascript" to type="text/javascript"?And Eric, how would it look in PHP? Aren't JavaScript and PHP the two languages most similar in syntax (if, else, switch, for, etc.)? It should be able to convert. Maybe using math.random() and background image based on result.

Link to comment
Share on other sites

*code removed*I've never gotten a reply on this saying if anyone is using it, and I don't want people stealing my code and not giving thanks.Not even the topic starter could comment on it, with either "thanks for this" or "I still would prefer a JS one"So I'm removing the code. Edited by Eric
Link to comment
Share on other sites

I'm making a website, where I need to be able to switch background image randomly for each load. Can anyone help me with this? I know I have to create an array of variables, but I don't know how to write the actual code.

One way to do this in JavaSript is to use Math.random() then check the number in an if statement, each different if statement writes a different image to the page backgroundbut theres probably a ton of other ways, this was just of the top of the head.
<script>var rand_int=Math.floor(Math.random()*3);if(rand_int==0){document.write('<style>body{background-image:url(http://www.google.co.uk/intl/en_uk/images/logo.gif);}</style>');}else if(rand_int==1){document.write('<style>body{background-image:url(http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif);}</style>');}else if(rand_int==2){document.write('<style>body{background-image:url(http://w3schools.invisionzone.com/style_images/w3sbanner.gif);}</style>');}else alert("Problem with random number");</script>

Link to comment
Share on other sites

I suppose.  So did my little script help  you?

No, I don't have a php server. And why did you remove your code? I read your post, but it's a non-reason. Everybody steals/sneaks peeks at code on the net. As long as people learn something from it for the future, that's payment enough. If people do that, I don't care if they steal my code/design, cause I know they'll eventually try and write their own one day, instead of copying whatever code and continually pasting it into their new site (code).
Link to comment
Share on other sites

*code removed*I've never gotten a reply on this saying if anyone is using it, and I don't want people stealing my code and not giving thanks.Not even the topic starter could comment on it, with either "thanks for this" or "I still would prefer a JS one"So I'm removing the code.

What is so special about your code...if it is as you said just a few lines of PHP. It is not like you have coded a whole page or application that someone could sell or something...There are probably tons of snippets out there to give a random bg image.This seems a little 3rd grade to me...don't look at me or i'll tell :)
Link to comment
Share on other sites

  • 1 month later...

bumpity bump, 'cuz i fixed it :)check the last line syntax for the else... should be:

else { alert("Problem with random number"); }

yep, those two stupid curly brackets threw off the whole script! I hate when that happens :)

Link to comment
Share on other sites

That shouldn't have made a difference, you only need {} if the code goes onto more than one line, in this case the code is:else alert("Problem with random number");which is all on one line so the brackets arent required.Try it without the brackets and it should work fine.

Link to comment
Share on other sites

That shouldn't have made a difference, you only need {} if the code goes onto more than one line, in this case the code is:else alert("Problem with random number");which is all on one line so the brackets arent required.Try it without the brackets and it should work fine.

darn it, you're right. And here I thought I was fixing something...So why isn't the code working?( http://home.no.net/jonvel/script/background.js )wait, I may have it now. It's in the CSS!Jonas, take the background-image definiation out of your CSS sheet. Since the link to the css sheet comes after the javascript, it takes priority. just take that one line out of your CSS file and see if that doesn't fix it.
Link to comment
Share on other sites

I would also think that you have correctly identified the problem, you have fixed something :)
yeah, just did some testing and it looks like if the background-image is removed from the CSS file, the javascript kicks in fine./me dances the 'does the I fixed something' jig :)I'm gonna PM Jonas now :(
Link to comment
Share on other sites

darn it, you're right. And here I thought I was fixing something...So why isn't the code working?( http://home.no.net/jonvel/script/background.js )wait, I may have it now. It's in the CSS!Jonas, take the background-image definiation out of your CSS sheet. Since the link to the css sheet comes after the javascript, it takes priority. just take that one line out of your CSS file and see if that doesn't fix it.

Nah, that doesn't fix it. I just get a default white background. But now I could use a php script if I wanted to, so maybe that's a solution. But oh no, Eric removed his script.
Link to comment
Share on other sites

One sec, i'll put a script together.

<script type="text/javascript">x=new Array();x[0]="image one"x[1]="image two"//keep going, you get the idea.random = Math.floor(Math.random()*x.length);startTep='<style type="text/css">body {background:url('+x[random]+');}</style>'document.write(startTep);</script>

Does that work?

Link to comment
Share on other sites

Ok. Got it. :)Rename your page to pagename.php, first of all.Next, put this in the head section, AFTER the CSS.

<?php$randthing = rand(1,max number here);#Where it says max..., put the last number that can be included. 1,20 means #a number between 1 and 20, AND including 1 and 20. switch($randthing){  case "1":  $finstyle="url of first image";  break;  case "2":  $finstyle="url of second image";  break;  case "3":  $finstyle="url of third image";  break;  #Ok, you get the idea. Continue with that format until done.  default:  exit("OMG IT DOESN'T WORK LOLOLOLOL");  #K, put the message that displays if it doesn't work there.   break;}$omgfirst='<style type="text/css">body{background-image:url(';$omglast=');}</style>';echo $omgfirst.$finstyle.$omglast;?>
K, you know how bad I am at php. So try that out. :)
Link to comment
Share on other sites

Wouldn't:

<script type='text/javascript'>var randomBG = [];randomBG[0] = "http://here.here.com/image.jpg";randomBG[1] = "http://here.here.com/image.jpg";randomBG[2] = "http://here.here.com/image.jpg";randomBG[3] = "http://here.here.com/image.jpg";var rand = Math.floor( Math.random() * randomBG.length );document.getElementsByTagName('BODY')[0].style.backgroundImage = 'url(' + randomBG[rand] + ')';</script>

Work?

Link to comment
Share on other sites

Whew, lots of scripts here. People are so eager to help... :)

Yes this works,  but so does mine.  There are two problems here:1) Neither of them work in opera, which Jonas uses2) The page Jonas pasted earler, http://home.no.net/jonvel/, does not work in IE or FF so there must be a problem with how it has been implemented.

I know the second one doesn't work in IE or FF, checked that. Could it have something to do with the way I escape the quotation signs?
Ok. Got it. :)Rename your page to pagename.php, first of all.

What do you mean, rename the page to pagename.php? Why? Isn't index.php ok?
Wouldn't:
<script type='text/javascript'>var randomBG = [];randomBG[0] = "http://here.here.com/image.jpg";randomBG[1] = "http://here.here.com/image.jpg";randomBG[2] = "http://here.here.com/image.jpg";randomBG[3] = "http://here.here.com/image.jpg";var rand = Math.floor( Math.random() * randomBG.length );document.getElementsByTagName('BODY')[0].style.backgroundImage = 'url(' + randomBG[rand] + ')';</script>

Work?

Nope, that doesn't work... :(
Link to comment
Share on other sites

Ok, Choco, that php script seems to work just fine, and being executed on the server, it's browser independant. Only one thing I'm curious about, is it possible to use php in a way so that you still get structured html when you look at the output html code? I'm kind of a neat freak that way... :)Say I wanted the result to look like this:

    <style type="text/css">      body {        background: url('background_URL');      }    </style>

http://home.no.net/jonvel/Cool. :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...