HTML Goodies: Script Tip: Week 62

By Joe Burns


Pokemon Tip...

     If a user has come to your page and didn't play nice with this script and allowed it to simply read "Nobody" by hitting return, we should make a point of showing that person the error of their ways and give them a second chance. That's what we'll do today.

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

     Here's the code we're interested in:

if (GuestName=="Nobody")
GuestName=window.prompt("Hello again!!!"+"\n"+"Last time you didn't tell me your name. Maybe you want to do it now?","Nobody");

if ((GuestName!="Nobody")&&(GuestName!=null))
{document.cookie=cookie_name+"="+GuestName+"; expires=Tuesday, 05-Apr-2010 05:00:00 GMT";}

if (GuestName==null) GuestName="Nobody"; }

     This little blip of code is the annoyer. It will only come into play if a cookie has been set and the person is returning. The script will never incorporate this code if there is no cookie mainly because of the code's placement. Let's see how it works.

     We start with another familiar If statement asking if the value of "GuestName" is equal to "Nobody". If so, a prompt is fired up and the user is again asked to put in their name.

     Notice the \n in the window.prompt. That represents a new line to JavaScript so this won't all be run together.

     Again, the default is set to "Nobody".

     Now we need to set the cookie off of what the user did. The next line tests for that. The double & means "and". So we're testing here if the value of "GuestName" is not equal (!=) to Nobody and not equal to nothing (null). If that's the case, meaning at least something was put in the text box, then it is set to a cookie.

     The next line is the catch-all if the user blanks the text box and goes on. The code tests if "Guestname" is equal to null. If it is, the value is reset to "Nobody". We can now be pretty sure that the user will get this warning again when they stop back.

     That's the extent of what we need to do to set the cookie. Next week, we talk about grabbing it and posting it to the page.

Next Week: Grab Yourself a Cookie!

     Do YOU have a Script Tip you'd like to share? How about suggesting a Script Tip to write about? I'd love to hear it. Write me at: jburns@htmlgoodies.com.

Learn to write your own JavaScripts with the HTML Goodies 30-Step Primer Series

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date