|
CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.
This is a 
|
|
Example
Session cookies' finest hours often occur behind the scenes, and as
part of a larger equation. Inter-page surveys or popup-once windows are
classic examples of this.
With that in mind then, here is a crude demonstration whereby the user
can customize the color of the document's background, with this color then
applied to all pages on the site:
Demo:
Source:
|
<script type="text/javascript">
//Get cookie routine by Shelley Powers
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function setcolor(what){
document.body.style.backgroundColor=what
document.cookie="bgcolor="+what
}
if (get_cookie("bgcolor")!="")
document.body.style.backgroundColor=get_cookie("bgcolor")
</script>
<form name="a1">
<p><select name="a2" size="1">
<option selected value="white">Select background color </option>
<option value="#F0F0F0">Light gray</option>
<option value="#80FFFF">Sky blue</option>
<option value="#C6C6FF">Purple</option>
<option value="white">White</option>
</select>
<input type="button" value="Go"
onClick="setcolor(document.a1.a2.options[document.a1.a2.selectedIndex].value)"></p>
</form>
|
Try reloading or navigating away then back to this page; the selected
background color persists. To extend this persistence to all pages on your
site, you would simply include the get_cookie routine and the two lines of
code that set the document's background on these pages.
Here is an additional page to illustrate this.
And on that note we conclude this tutorial. Enjoy JavaScript cookies,
but like everything else in life, in moderation!
|