Register Your Name with the Cookie-Meister

Please enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.

Enter your name:



<SCRIPT>

function setCookie(name, value, expires) {
     document.cookie = name + "=" + escape(value) +
                                    ((expires) ? "; expires=" + expires.toGMTString() : "");
}

function getCookie(name) {
     var prefix = name + "=";
     var begin = document.cookie.indexOf(prefix);

     if (begin == -1) return null;

     var end = document.cookie.indexOf(";", begin);

     if (end == -1) end = document.cookie.length;

     return unescape(document.cookie.substring(begin + prefix.length, end));
}

function register(name) {
     var expiration = new Date();

     expiration.setYear(expiration.getYear() + 1);

     setCookie("TheCoolJavaScriptPage", name, expiration);
}

</SCRIPT>

<H1>Register Your Name with the Cookie-Meister</H1>

<SCRIPT>

// get the "TheCoolJavaScriptPage" if it exist
var yourname = getCookie("TheCoolJavaScriptPage")

// if the cookie yourname exist then write out the Name
if (yourname) document.write("<P>Welcome Back, ", yourname)
// else if the cookie yourname does not exist then write out "You haven't ....
else document.write("<P>You haven't been here in the last year...")

</SCRIPT>

Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.

<FORM onSubmit="return false">
     Enter your name: <INPUT TYPE="text" NAME="username">
     <INPUT TYPE="button" value="Register"
      
onClick="register(this.form.username.value); history.go(0)">
</FORM>

onClick call the function register() & pass it the User's Name
register() set the expiration time for the cookie & then calls the setCookie() function where we create the "actual" cookie.

history.go(0) means go no where but reload the page so that we can check for cookie values.