0

I have added a background color change effect to my website. Now I want that change to apply to all my other pages. I'm having trouble understanding cookie functions, so some context with what I'm working on would really help.

My JS:
function background(color){document.body.style.backgroundColor=color;}

My HTML:
<tr><td class="bggreen" style="cursor: pointer" onclick="background('green')">&nbsp;</td></tr>

My CSS:
.bggreen { background-color: green; }

The code all works fine, so some of this info might be pointless. It's just, if I were to construct a cookie to make these color changes apply to all relevant pages in my site, how would I go about? No preference to whether PHP or JS is used. I would just like what comes most practically.

Jason Chen
  • 2,487
  • 5
  • 25
  • 44

1 Answers1

1

Here are some simple cookie functions I use from javascript. You can store the latest color value in the cookie and then upon initialization of the page, you can read the value from the cookie and set the color appropriately:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

name and value are strings. days is a number of days until the cookie expires.

So, whenever you change the color, you could do this:

function background(color){
    document.body.style.backgroundColor = color;
    createCookie("backgroundColor", color, 365);
}

And, when the page first loads, you could do this:

var color = readCookie("backgroundColor");
if (color) {
    document.body.style.backgroundColor = color;
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979