OK! The cookie is set. Now we need to use coding to go get it. In the case of this script, the display is immediately after setting the cookie. Keep in mind that that doesn’t always have to be the case. You can easily split this code up and set on one page but grab and display on another. That’s the purpose of these cookies – to carry information across pages.
Try out the Script
Note that if you’ve tried the script before,
it won’t give you the prompt – it’ll just say hello.
Here’s the Code
This blip of code is going to look very similar to the one we looked at in Script Tip 61. The reason is because the two perform the same duties only one grabs the text string from the cookie to assign it to the variable “GuestName” and this one will grab it so it can be displayed. Here’s the code:
This is a function so there has to be something to trigger it. Look at the very bottom line of the script. See how “GuestName” is equal to the function getName. That’s what fires it up. The entire script must be put into the browser memory, then the last line fires this function by calling for its output.
So here we go. If there is a document.cookie (which we know exists – at least in this format), then “index” equals what is contained in the cookie “NameCookie2010”.
If the index is non existent (-1), then “namestart” is equal to the equal sign plus one to the length.
Then “nameend” is equal to the rest of that line until the end represented by the semicolon. Remember all of this two tips ago?
If there is no end to the string (nameend==-1) then “nameend” is equal to the full length of the cookie. This would come into play if no expiration date was set. “Guestname” is then going to be given the value of what is between “namestart” and “nameend” which is what the user put in.
Finally, the script is told to return that value.
The next line is what fired up the entire process in the first place triggering the first function we looked at, putCookie(). You know the next line, it fires up the function we just looked at.
Once “GuestName” is given the value of what is contaned in the cookie, you can place it anywhere on the page using document.write statements. Here’s what the author used:
The text appears and the name is displayed.
So there you go. A cookie is set and retrieved. It’s a great script, but I do see one problem with it. After a cookie is set, the text will always read “Nice to meet you”. Well, after ten visits – you’re not meeting me anymore.
I took the script, altered it a bit and got it to display the “nice to meet you” greeting the first time is displayed. Each time after that, it will read “Welcome back”. I’ll show how to do that next week.
Next Time: Welcome Back!