Solved

Swapping background images on browser refresh.

Posted on 2004-10-07
10
264 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
  • 5
  • 5
10 Comments
 

Author Comment

by:kearnguy
Comment Utility
Maybe an increase of points will encourage an answer :)
0
 
LVL 3

Expert Comment

by:hemebond
Comment Utility
<!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
Comment Utility
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
 
LVL 3

Accepted Solution

by:
hemebond earned 200 total points
Comment Utility
"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
Comment Utility
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 3

Expert Comment

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

Author Comment

by:kearnguy
Comment Utility
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
Comment Utility
It does explain things. It also means the script I gave you is not entirely correct.
0
 

Author Comment

by:kearnguy
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
This article discusses how to create an extensible mechanism for linked drop downs.
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…

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now