JavaScript : Smart Sites and Cute Cookies
Dr Benton
Function for Linking a Cookie to an HTML page
The final step is to deal with the form. As soon as a visitor enters his name in the form, the cookie management process must
kick in. Change the name field as follows:
<INPUT TYPE="text" NAME="nom" SIZE="15" VALUE="" onChange=verifieSiDansCookie()>
The
onChange event is detected as soon as the visitor leaves the input field for the name, and the function
verifieSiDansCookie() is initiated. The latter triggers cookie handling according to the form content. Add the following code between the
<BODY> and
<BODY> tags:
<SCRIPT>
function verifieSiDansCookie()
{
var votreNom = document.forms[0].nom.value;
var nom = litCookie(votreNom);
u = nom.indexOf("=");
nom = nom.substr(u+1, nom.length);
if (nom != "")
{
document.forms[0].sortie.value = "Hello " + votreNom + ". You've now visited us "
+ nombreVisites + " times.";
}
else
{
document.forms[0].sortie.value = "Welcome to our site " + votreNom + ". Enjoy your
first visit.";
miseAJour(votreNom);
}
}
</SCRIPT>
Our function reads the name entered in the form and saves it in the variable
votreNom. The function
litCookie is then called up and given the name in
votreNom to obtain the name of the cookie. We then look for this name among all the cookies existing on the user's system. If it is
found (
if (nom != "")), which means that the user has already visited the site, the number of visits is displayed. If not, we just display a welcoming
message and save a new cookie.
That's it!
All our page code has now been written! Pop it in the oven, bake it at 180 °C for 20 minutes, then
serve it up here!
Be careful with accents. This script cannot work if the user enters a name with accents or the separating character used for writing the cookie data.
To avoid this problem, you should check the form content.
You now have the technical knowledge so let your imagination do the rest. For instance, why not offer your visitors a list
of home pages to choose from, and direct them towards the one they have selected each time they return.