Page 1 of 3 123 LastLast
Results 1 to 10 of 21

Thread: Changing background image script

  1. #1
    Join Date
    Mar 2005
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Changing background image script

    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

  2. #2
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by ulrich
    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=bg
    You should consider abandoning the use of presentational attributes and their script equivalents.

    An entirely different approach could be:

    Code:
    #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:

    Code:
    <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 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

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,127
    Thanks
    44
    Thanked 3,228 Times in 3,189 Posts
    Blog Entries
    12

    Default

    I was playing around with this and came up with this admitted monstrosity that actually works:

    HTML Code:
    <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>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. #4
    Join Date
    May 2005
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Background Images - sized for Browser

    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 ??

  5. #5
    Join Date
    Aug 2005
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1
    I was playing around with this and came up with this admitted monstrosity that actually works:

    HTML Code:
    <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.

    Code:
    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
    }

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,127
    Thanks
    44
    Thanked 3,228 Times in 3,189 Posts
    Blog Entries
    12

    Default

    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:
    Code:
    <!--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'.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Aug 2005
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,127
    Thanks
    44
    Thanked 3,228 Times in 3,189 Posts
    Blog Entries
    12

    Default

    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.
    Code:
    <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:
    HTML Code:
    <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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Aug 2005
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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:

    Code:
    <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:

    Code:
    <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

  10. #10
    Join Date
    Sep 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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!!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •