PDA

View Full Version : Changing background image script



ulrich
05-05-2005, 04:14 PM
Hi,
I am looking for a script that change a background image of a website with an onClick button or a mouseover task. The background should remained even if we refresh the page on the browser.

I have one "onMouseover background change", but it's does'nt remained when refreshing the browser:


<HEAD>
<script type="text/javascript">
function bgChange(bg)
{
document.body.background=bg
}
</script>
</HEAD>

<BODY>
<table width="20" height="20">
<tr>
<td onmouseover="bgChange('Background1.jpg')"
background="Background2.jpg">

</td>
</tr>
</table>
</BODY>

Thank you for help :)

mwinter
05-05-2005, 10:19 PM
I am looking for a script that change a background image of a website with an onClick button or a mouseover task. The background should remained even if we refresh the page on the browser.HTTP is stateless, so that is not simple to achieve reliably. You could store this information in a cookie, though of course cookies can be disabled. It would also be possible to send the information in the URL, but that isn't practical in this case.


document.body.background=bgYou should consider abandoning the use of presentational attributes and their script equivalents.

An entirely different approach could be:


#some-cell {
background: #ffffff url(Background2.jpg);
color: #000000;
}

#some-cell:hover,
#some-cell.mouseover {
background-image: url(Background1.jpg);
}


<td id="some-cell" onmouseover="this.className = 'mouseover';">
<!-- ... -->
</td>This would work on modern user agents with or without script support. For IE, and other lesser programs, it alters the class attribute.

The equivalent style alteration would be:


<td ... onmouseover="if(this.style) {this.style.backgroundImage = 'url(Background1.jpg)';}">

If you want to go down the cookie road, I've posted cookie utilities (http://www.dynamicdrive.com/forums/showpost.php?p=7692&postcount=4) in the past (you'll need both attached text files, renamed to .js of course). The cookie object uses the interface of my Hashtable object, which is well documented in the source code, and follows the Java implementation very closely. The only extra method is isSupported, which tests whether cookie support is available.

Mike

jscheuer1
05-06-2005, 04:49 AM
I was playing around with this and came up with this admitted monstrosity that actually works:


<html>
<HEAD>
<title>Change Background Persist - Demo</title>
<script type="text/javascript">
//Set Config="yes" and run a few cycles and refresh page twice
// to clear cookie when changing the Background Images Array.
//Set to "no" for normal operation.
var Config="no"

//Set Background Images Array, use at least two Images.
//Do NOT use =, +, -, or spaces in path or filenames.
var backgs=new Array
backgs[0]="photo1.jpg"
backgs[1]="photo2.jpg"
backgs[2]="photo3.jpg"

/////////No Editing Needed for rest of Script////////
function bgChange(){
for (i = 0; i < backgs.length; i++){
if (document.body.background!==backgs[i]){
document.body.background=backgs[i]
break
}
}
if (backgs.length>2)
backgs.push([backgs.shift()])
}
</script>
</HEAD>
<BODY text=white bgcolor=black background=photo1.jpg>
<input type=button value="Change Background Image" onClick="bgChange()">
<!--Keep Below Script unchanged as the last thing in the <BODY> </BODY> section-->
<script type="text/javascript">
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
var cookiename="bgchange"
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.body.background=cookievalue
var acookiename="abgchange"
var acookievalue=get_cookie(acookiename)
if (Config!=='yes'){
if (acookievalue!="")
backgs=eval(acookievalue)
}
}

function saveBgrnd(){
var cookiename="bgchange"
var cookievalue=document.body.background+";path=/"
document.cookie=cookiename+"="+cookievalue
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"
var acookievalue=abackgs+";path=/"
document.cookie=acookiename+"="+acookievalue
}

if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction

window.onunload=saveBgrnd

</script>
</BODY>
</html>

lodgest
05-09-2005, 03:38 PM
I'm new to JavaScript, but am trying to create a page that will load a different background image depending on the size of the browser.
I have found code that will allow me to insert a different image based on 800 1024 or whatever size, but can't get it to work with background images.
Not sure if it's my total inability to code,or whether it's not possible to do.

Any ideas please ??

Gyve
08-08-2005, 07:07 PM
I was playing around with this and came up with this admitted monstrosity that actually works:


<html>
<HEAD>
<title>Change Background Persist - Demo</title>
<script type="text/javascript">
//Set Config="yes" and run a few cycles and refresh page twice
// to clear cookie when changing the Background Images Array.
//Set to "no" for normal operation.
var Config="no"

//Set Background Images Array, use at least two Images.
//Do NOT use =, +, -, or spaces in path or filenames.
var backgs=new Array
backgs[0]="photo1.jpg"
backgs[1]="photo2.jpg"
backgs[2]="photo3.jpg"

/////////No Editing Needed for rest of Script////////
function bgChange(){
for (i = 0; i < backgs.length; i++){
if (document.body.background!==backgs[i]){
document.body.background=backgs[i]
break
}
}
if (backgs.length>2)
backgs.push([backgs.shift()])
}
</script>
</HEAD>
<BODY text=white bgcolor=black background=photo1.jpg>
<input type=button value="Change Background Image" onClick="bgChange()">
<!--Keep Below Script unchanged as the last thing in the <BODY> </BODY> section-->
<script type="text/javascript">
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
var cookiename="bgchange"
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.body.background=cookievalue
var acookiename="abgchange"
var acookievalue=get_cookie(acookiename)
if (Config!=='yes'){
if (acookievalue!="")
backgs=eval(acookievalue)
}
}

function saveBgrnd(){
var cookiename="bgchange"
var cookievalue=document.body.background+";path=/"
document.cookie=cookiename+"="+cookievalue
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"
var acookievalue=abackgs+";path=/"
document.cookie=acookiename+"="+acookievalue
}

if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction

window.onunload=saveBgrnd

</script>
</BODY>
</html>

I like this script a lot, however the cookie expires imediately after the user closes the browser. I tried modding your savebackground fxn (below) but it doesn't work. Any help would be much appreciated. Thank you.


function saveBgrnd(){
var cookiename="bgchange"
var cookievalue=document.getElementById('Good').style.backgroundImage+";path=/"
document.cookie=cookiename+"="+cookievalue
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"

//I added this section:
var date = new Date();
date.setTime(date.getTime()+(20*24*60*60*1000)); //20 days
var expires = "; expires="+date.toGMTString();

var acookievalue=abackgs+expires+";path=/"
// it was this before: var acookievalue=abackgs+";path=/" I added expires.
document.cookie=acookiename+"="+acookievalue
}

jscheuer1
08-09-2005, 07:58 AM
Your syntax seems correct, with the possible exception of spacing. I noticed some other problems with the script. Try this for the final script on the page:

<!--Keep Below Script unchanged as the last thing in the <BODY> </BODY> section-->
<script type="text/javascript">
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
var cookiename="bgchange"
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.body.background=eval(cookievalue)[0]
var acookiename="abgchange"
var acookievalue=get_cookie(acookiename)
if (Config!=='yes'){
if (acookievalue!="")
backgs=eval(acookievalue)
}
}

function saveBgrnd(){
var cookiename="bgchange"
var cookievalue=document.body.background+";path=/"
document.cookie=cookiename+"="+cookievalue
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"
var date = new Date();
date.setTime(date.getTime()+(20*24*60*60*1000)); //20 days
var expires = "; expires="+date.toGMTString();
var acookievalue=abackgs+expires+"; path=/"
document.cookie=acookiename+"="+acookievalue
}

if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction

window.onunload=saveBgrnd

</script>Works here.

NOTE: When working with cookies it is often a good idea to use your browser's delete cookies button from time to time so as to be working from a 'clean slate'.

Gyve
08-09-2005, 10:38 AM
Wow that works like a charm. Thank you!
I just have one more question, it is not possible to overide the cookie once it is stored. For example once you change the background again it stays as the first one chosen. Also, the var Config is for setting up new images?

Thanks,
Gyve

jscheuer1
08-09-2005, 02:48 PM
OK, it was working fine in IE but when I loaded it up in FF, I saw some very odd behaviors. I've updated, consolidated and improved the script. It now goes entirely in the head and can handle initial backgrounds set with either style or with HTML. Expiration date is configurable and optional. I've eliminated the Config option as it was confusing. When configuring the script (as with all cookie scripts), exit the page and with the browser open to a different page, use the browser's delete cookies button to clear all cookies, then exit all instances of the browser. Now you can make whatever changes you want to the page, then launch it to check your work.

<script type="text/javascript">

/*Background Change Script w/cookie persistence
2006 John Davenport Scheuer (jscheuer1)
this credit must remain for legal use
visit Dynamic Drive Help Forums (http://www.dynamicdrive.com/forums/) */

//Set expiration in days, use 0 for session only cookie
var exp=20

//Set Background Images Array, use at least two Images.
//Do NOT use =, +, -, or spaces in path or filenames.
//For best results, set body's background to the first entry
var backgs=new Array
backgs[0]="photo1.jpg"
backgs[1]="photo2.jpg"
backgs[2]="photo3.jpg"

/////////No Editing Needed for rest of Script////////
function bgChange(){
if (backgs.length>2)
backgs.push([backgs.shift()])
for (i = 0; i < backgs.length; i++)
if (document.body.background!==backgs[i]||document.body.style.backgroundImage.toLowerCase()!=='url('+backgs[i].toLowerCase()+')'){
document.body.style.backgroundImage='url('+backgs[i]+')'
break
}
}

function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
var acookiename="abgchange"
var acookievalue=get_cookie(acookiename)
if (acookievalue!=""){
backgs=eval(acookievalue)
document.body.style.backgroundImage='url('+backgs[0]+')'
}
}

function saveBgrnd(){
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"
var date = new Date();
date.setTime(date.getTime()+(exp*24*60*60*1000));
var expires = exp? "; expires="+date.toGMTString() : ""
var acookievalue=abackgs+expires+"; path=/"
document.cookie=acookiename+"="+acookievalue
}

if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", onloadfunction, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", onloadfunction );
}
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = function ( e ) {
oldOnload( e );
onloadfunction();
};
}
else
window.onload = onloadfunction;
}

window.onunload=saveBgrnd

</script>You can still use this:

<input type=button value="Change Background Image" onClick="bgChange()">or variations of it, in the body to allow users to page through the available backgrounds.

Gyve
08-09-2005, 06:17 PM
Wow thank you John for the fast response. I have been racking my brains out on this all day. Your code works perfectly. I have been trying to get it to fit my constraints and it just doesn't work. Any ideas what I am doing wrong would be greatly appreciated.

I have created and internal stylesheet which looks like this:


<style type="text/css">
.Good {background-image: url(images/MainPageImages/backgrounds/flowerpotty.jpg); background-repeat: no-repeat; background-position:center; }
</style>


I have a table cell which carries the ID and Class "Good".

My <script> is this:


<script type"text/javascript">

var backgs = new Array();
backgs[0] = "url(images/image1.jpg)";
backgs[1] = "url(images/image2.jpg)";
backgs[2] = "url(images/image3.jpg)";
backgs[3] = "url(images/image4.jpg)";

//Here is my function which changes an image when the hyperlink : //javascript:changeImage(1) is pressed.

function changeImage(which) {
newImage = backgs[which];
document.getElementById('Good').style.backgroundImage = newImage;
}
</script>

I have been trying to make your cookie script dynamic so that one can select the image to change to and apply to a stylesheet (so that it can apply to any cell not just the body tag). I got the dynamic cell background rotation, but I can't get it to be recoreded properly in a cookie to be saved.
If you have time to point out my mistakes I would greatly appreciate it.

Thanks,
Gyve

SivoxII
09-26-2006, 08:21 PM
You guys are "SIMPLY THE BEST!!!!!"

I have been looking for a script to do this for a VERY long time.

Thank you so much.

(if you would like to see the final result, due to your coding skills, please feel free to check out the front page of our website at http://www.accessokanagan.com)

Cheers!! :)

calavera
08-11-2007, 12:07 AM
This is so nice! But how can I use this code to create let's say 4 links with the name: white, black, red, yellow and when I hover over them, to load white.gif, black.gif, red.gif, yellow.gif (each image with their own link, of course) ? Actually, I have managed to do this with some modifications (not good ones thought) but I don't know how to store them into cookies so that image from the specified link to remain. Thank you and sorry for posting in such old thread.

Sliight
08-11-2007, 01:17 AM
Neat looking site... one thing though, the white fonts you use in the fading green to white menu bars. It's very hard to see the words, "front page", "departments" and "around the valley". The top menu bars are not as close to invisible in white as the others, but they are not super easy to see. I checked out the site using Firefox btw...

bwx
09-11-2007, 06:37 PM
Hey
I'm looking for about the same script, but waht i actually want is a script that randomly changes the background. So i provide say 10 backgrounds, and the background is randomly chosen on each page. Could that be possible with - a modification of - this script?
Thanks!
Bruno

tetrix
05-01-2008, 01:38 PM
anyone knows if it's possible to add a fade effect(for now im trying on ie) in the background slide show: i'm tryng something like this:

document.body.background.filter="blendTrans(duration=2)"

but looks like this parent-son hierachy dont work, it works when i dont apply the blendTrans filter(something like this): document.body.background = Pic[j];

i read thru the msdn and they say that blendTrans can be applied to the body object.

?

jscheuer1
05-01-2008, 03:18 PM
Not to the code in this thread, no. For Trans filters to work, there must be a more dramatic change to the element (in this case, the body) than its background style.

tetrix
05-02-2008, 10:28 AM
thanks for your reply,would this mean that the body element needs to be created 'on the fly'?

jscheuer1
05-02-2008, 01:03 PM
thanks for your reply,would this mean that the body element needs to be created 'on the fly'?

Er, well that might be a way to do it, but is fraught with other issues if you do. I was thinking, and there is at least one other thread around close to this idea, of using foreground images, but positioning them absolutely or fixed and behind all of the other content of the page. And not just the images, but rather their containers, such that one would then basically have a slide show like Ultimate-Fade or Swiss Army, both of which can do a fade transition of sorts in most modern browsers including IE.

Ah, here's one such thread:

http://www.dynamicdrive.com/forums/showthread.php?t=29584

tetrix
05-03-2008, 12:11 PM
thanks for the link, yep i think that might do the trick because the other way seems very interesting but for now a bit over my skills :), the "cheat" way could also be embellish with a scrollbar hiding to get a more backround image feeling

peacebrother
05-25-2010, 09:30 PM
Hi!
I'm trying to apply this code to a site I'm working on which uses animated gifs for background images. It seems this code only works if you've included the background image in the body tag. For some reason I can't get the starting animated gif to work as a background image when include it in the body tag. I can only get the background to show up if I include it as css like this:

<style type="text/css">
body {
background:url(images/comp4ggg.gif);
background-repeat:repeat;
}
</style>


Does anyone know if there's a way to change the css in the head with an onMouseover command? I'm looking to have the tiled gifs change when you hover over a series of links.

If not, is there some way to get the animated gif to work in the body tag?

I realize it's probably not the best idea to be using the gifs as backgrounds but we're going for an oldschool/bad design aesthetic on this project.

thanks.

ioseph
08-01-2011, 12:09 PM
Hi,

I've been looking for something like this. This works great.

Please, could someone advice how to adjust the script to change the background images also in backward direction. So than I'll have 2 buttons, Forward and Backward.
Thanks!

jscheuer1
08-01-2011, 02:46 PM
Hi,

I've been looking for something like this. This works great.

Please, could someone advice how to adjust the script to change the background images also in backward direction. So than I'll have 2 buttons, Forward and Backward.
Thanks!

There are at least several version of a rotating background image script in this thread, including one linked in from another thread.


Which one are you using?


In detail, what all do you want it to do?


Do you have a page setup on the web that shows what you have so far?