Solved

Swapping background images on browser refresh.

Posted on 2004-10-07
10
271 Views
Last Modified: 2008-03-10
I am in need of a javascript that sets a cookie which enables a background image to change everytime refresh is used.  Also I would like to make the cookie timed so that the background image would change for a couple days if the user returned to the site in the time period.

I have seen a script in a question on this site (http://www.experts-exchange.com/Web/Q_20744767.html?query=swap+background&topics=96) that I thought would work, however it has some other image function in it that I don't want.  I tried to remove the stuff that I didn't want but I couldn't get it to work.

I tried writing my own cookie with "document.cookie", but haven't learned enough about JS yet to know how to check for it and have something else executed if the cookie is present...

If there is a better way to this without using a cookie, let me know that too.

Thanks for all your help in advance.
0
Comment
Question by:kearnguy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
10 Comments
 

Author Comment

by:kearnguy
ID: 12263908
Maybe an increase of points will encourage an answer :)
0
 
LVL 3

Expert Comment

by:hemebond
ID: 12265139
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
      <head>
            <title>Q_21160225</title>
      </head>
      <body>
      </body>
      <script type="text/javascript">
            var list = new Array("/images/1.jpeg","/images/2.jpeg","/images/3.jpeg");

            var bg = (document.cookie == '') ? null : document.cookie.split(';');
            if(bg)
            {
                  bg = bg[0].split('=');
            }

            var expiry_date = new Date();
            expiry_date.setMonth((expiry_date.getMonth() + 1));

            if(list.length)
            {
                  i = (bg) ? bg[1] : Math.round(Math.random() * (list.length - 1));
                  document.getElementsByTagName('body')[0].style.backgroundImage = 'url("' + list[i] + '")';
                  document.cookie = "bg=" + i + ";expires=" + expiry_date.toGMTString();
            }
      </script>
</html>
0
 

Author Comment

by:kearnguy
ID: 12266329
The above code successfully loads the first image as the background, but nothing happens when I refresh the page or go back to it later on.  The background image stays the same.

Am I doing something wrong?  All I did different was change the pic array path to:
   
   var list = new Array("one.gif","two.gif","three.gif");

...since the pictures and the HTML file are in the same folder.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 3

Accepted Solution

by:
hemebond earned 200 total points
ID: 12272760
"Also I would like to make the cookie timed so that the background image would change for a couple days if the user returned to the site in the time period." I took this to mean you wanted the image to remain the same for a certain duration. Otherwise the whole sentence makes absolutely no sense.

This code will change the background image on every refresh:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
      <head>
            <title>Q_21160225</title>
      </head>
      <body>
      </body>
      <script type="text/javascript">
            var list = new Array("/images/1.jpeg","/images/2.jpeg","/images/3.jpeg");
            if(list.length)
            {
                  i = Math.round(Math.random() * (list.length - 1));
                  document.getElementsByTagName('body')[0].style.backgroundImage = 'url("' + list[i] + '")';
            }
      </script>
</html>
0
 

Author Comment

by:kearnguy
ID: 12280531
What I meant was...

A cookie would be placed that would expire after a few days.  During the few days that the cookie is active, a user could return to the site and see a different background than the background that was loaded when they left.

My apologies if my less-than-great grammer confused you...I was in a hurry when I typed the original post and couldn't figure out an easy way to say what I needed to.  

This works fine though.  I'll try to figure out the expiry thing myself - what you gave me is what I really needed.  Points go to you.  

However, for future reference, allow me to gently bring something to your attention concerning communication with people less knowledgable than yourself.  Some people might take offense to someone telling them that they make "absolutely no sense" (specially when they are humble enough to ask for help in the first place).  A better approach might be to just ask for clarification.

Thanks again.
0
 
LVL 3

Expert Comment

by:hemebond
ID: 12280972
Then explain this to me. What happens when the cookie expires?
0
 

Author Comment

by:kearnguy
ID: 12282816
If the cookie expires and the user returns to the site, a new cookie is placed, and the cycle starts all over again.  For example:

On the particular site in question, the traffic patterns indicate that each user visit the site roughly 8 times in a one week period.  If the background cookie was set for 1 month the user could come back to the site for the entire month without ever seeing the same background image (provided I had close to 40 images in the array).  At the end of the month the cookie would expire and when the user comes back, they would start back at the top of the array of background images.

Hopefully that helps explain things.
0
 
LVL 3

Expert Comment

by:hemebond
ID: 12283639
It does explain things. It also means the script I gave you is not entirely correct.
0
 

Author Comment

by:kearnguy
ID: 12284010
Well,  your script did help quite a bit.  I couldn't even get the ones I was trying to swap the images.

If you would like to help me figure it out though by expanding on your answer, I will post a new topic and dish out some more points.  Otherwise I'll keep cracking away solo until I figure something out.

Let me know if you are interested in still working on this issue.
0
 
LVL 3

Expert Comment

by:hemebond
ID: 12292874
This will cycle through all available images. I don't see any reason to have it expire after a month. It'll go to the end of the list, and then start again. Ideally you should be doing this stuff server-side.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
      <head>
            <title>Q_21160225</title>
      </head>
      <body>
      </body>
      <script type="text/javascript">
            var list = new Array("/images/1.jpeg","/images/2.jpeg","/images/3.jpeg");
            var i = 0;

            var bg = (document.cookie == '') ? null : document.cookie.split(';');
            if(bg)
            {
                  bg = bg[0].split('=');
                  i = Number(bg[1]) + 1;
            }

            if(i >= list.length)
            {
                  i = 0;
            }
            document.getElementsByTagName('body')[0].style.backgroundImage = 'url("' + list[i] + '")';
            document.cookie = "bg=" + i;
      </script>
</html>

Keep the points.
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question