View Full Version : using cookies for name memory

Apr 30th, 2008, 07:35 PM
hi all.

i've recently created a casino royale style website. it asks the user to enter their full name (eg, james bond) then displays welcome bond, james bond. then has a blackjack game. a fruit machine and a dice game. however each time the user returns to the lobby (the home page) they are asked to enter their name again. im familiar with javascript but have always avoided the use of cookies. i always separate my javascript page to a separate html page. what is the code i need so the usernames are remembered. also do i have a further js page or can i add it to the original js page already linked to the home page. any help with this would be hugely appreciated.

Philip M
Apr 30th, 2008, 07:43 PM
A cookie will do the job just fine.

<script type = "text/javascript">

function createCookie(name,value,days) {
if (days) {
var date = new Date();
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); // set cookie to expire yesterday


var name = "playername" or whatever name you wish to give the cookie
var value = "James Bond"
var days = number of days cookie to remain active (say 7)

Apr 30th, 2008, 08:03 PM