JavaScript Cookies

(The below code should be used exactly without modification.)

The SetCookie function and the SetC functions define the cookie. This allows you to take user input (presumably from a form) and convert it into 'cookie' format. This code should be placed in the head of the HTML page. Use this code exactly as you see it.

The Source:
function SetCookie (name, value) { var argv = SetCookie.arguments; var argc = SetCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : ""); } function setC(form) { var expdate = new Date (); expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000 * 31)); SetCookie (form.name, form.value, expdate); }

The source below is an example defining how you should go about sending data to the SetCookie and SetC functions. Note: you can experiment with onChange, onClick, onFocus, onBlur depending on whether you are using a button, text box, radio, button. Email me with you problems.

The Source:
<form> <b>Enter your name: </b><input type=text size=30 name="msg1" onChange="setC(this)"> </form>

This code should be pasted into the HTML page where you want to display the cookie results. The GetCookieVal function and the GetCookie function find the cookies you created earlier and display them on the page.

The Source:
<script language="JavaScript"> // Get Cookie Value function function getCookieVal(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape (document.cookie.substring(offset, endstr)); } // Get Cookie function function GetCookie(name) { var arg = name+"="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return getCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } </script>

This final piece of code shows how to pull the cookie value from the GetCookieVal and GetCookie functions. Notice the 'msg1' variable is the same one specified from the form above. Experiment heavily with Cookies, they are among the most powerful features of JavaScript.

The Source:
var nam1=GetCookie("msg1") <script> document.linkColor=GetCookie("linkColor"); document.alinkColor=GetCookie("linkColor"); document.vlinkColor=GetCookie("linkColor"); document.bgColor=GetCookie("backColor"); </script>

Click here for a working demo of cookies