Common Scripts

 <  Day Day Up  >  


Before concluding the chapter, let's see a few examples of the useful scripts commonly found on the Web. The scripts here are provided only with modest explanation on their use. However, even JavaScript novices should be able to use them by copying them into their pages with little or no modification. Other copy-paste scripts can be found online at sites such as www. webreference .com/js and www.dynamicdrive.com.

Last Modification Date

A common use of script is to add small bits of content or HTML to a page dynamically. For example, consider the need to write a last modification date to the bottom of every document in a Web site. Using a short JavaScript at the bottom of a page could be quite easy, as illustrated here:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Last Modified Example  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   </head>   <body>  ...Page Content here...  <hr />   <div align="center">   <small>   &copy;  2003, Demo Company Inc.  <br />   <script type="text/javascript">  <!--   document.write("Document last modified: "+document.lastModified); //-->  </script>   </small>   </div>   </body>   </html>  

Using this script is quite easy: just take the script element and its contents and copy-paste it where you like in your document, and put markup elements around it or within the quotes for formatting.

Conditional Markup Inclusion

JavaScript is commonly used to add markup to a page in a conditional fashion. It is possible, using JavaScript, to detect the version of the browser in use and then produce some markup that fits. Consider the following example that produces a page with a <blink> tag if Netscape is detected or a <marquee> tag if Internet Explorer is in use:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Browser Detect Example  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   </head>   <body>   <script type="text/javascript">   <!--  var useragent=navigator.userAgent.toLowerCase();    var is_nav=((useragent.indexOf('mozilla')!=-1));    var is_ie=(useragent.indexOf("msie") != -1);     if (is_nav && !is_ie)       document.write("<blink>Netscape should blink</blink>");    else if (is_ie)        document.write("<marquee>IE loves the marquee</marquee>");    else       document.write("<strong>Strong for the unknown browser</strong>"); //-->  </script>   </body>   </html>  

Detection is not limited to a particular browser type, but to individual versions or even the support of a particular technology or plug-in. Readers interested in conditional page generation should review http://devedge.netscape.com/viewsource/2002/browser-detection/ or turn to a server-side tool such as BrowserHawk (www.browserhawk.com) rather than rolling their own detection routines.

Pull-down Menu Navigation

A common use of JavaScript is for navigation systems. Designers recently have begun to rely more and more on pull-down menu systems within a site for navigation to frequently accessed areas. The following example shows the use of JavaScript:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Select Navigation  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   <style type="text/css">  <!--    .nochoice   {color: black;}    .choice     {color: blue;} -->  </style>   <script type="text/javascript">   <!--  function redirect(pulldown)  {   newlocation = pulldown[pulldown.selectedIndex].value;   if (newlocation != "")    self.location = newlocation; }     function resetIfBlank(pulldown) {   possiblenewlocation = pulldown[pulldown.selectedIndex].value;   if (possiblenewlocation == "")     pulldown.selectedIndex = 0; /* reset to start since no movement */ } //-->  </script>   </head>   <body>   <form action="#" name="navForm" id="navForm">   <b>  Favorite Sites:  </b>   <select name="menu" id="menu" onchange="resetIfBlank(this);">   <option value="" class="nochoice" selected="selected">  Choose your site  </option>   <option value="" class="nochoice"></option>   <option value="" class="nochoice">  Search Sites  </option>   <option value="" class="nochoice">  ---------------------------  </option>   <option value="http://www.yahoo.com" class="choice">  Yahoo!  </option>   <option value="http://www.msn.com" class="choice">  MSN  </option>   <option value="http://www.google.com" class="choice">  Google  </option>   <option value="" class="nochoice"></option>   <option value="" class="nochoice">  Demos  </option>   <option value="" class="nochoice">  ---------------------------  </option>   <option value="http://www.democompany.com" class="choice">  Demo Company  </option>   </select>   <input type="button" value="go"   onclick="redirect(document.navForm.menu);" />   </form>   <script type="text/javascript">  <!--   document.navForm.menu.selectedIndex = 0; //-->  </script>   </body>   </html>  

Adding more choices to the menu is simply a matter of setting an <option> tag's class to "choice" and its value attribute to the URL of the document to load. Readers can remove the style sheet and class attributes if there is no interest in making choices and labels look different.

Note that this example requires the use of a button press to trigger a page load. However, it is easy enough to modify the script to make the menu trigger as soon as a choice is made. Change the <select> tag to trigger the redirect function using the onchange event handler, as shown here:

  <select name="menu" onchange="redirect(document.navForm.menu);">  

Readers should note that the use of pull-down navigation with such "hair triggers" does introduce some usability problems.

Rollover Buttons

JavaScript is also commonly used for page embellishment . One of the most common embellishments is the inclusion of rollover buttons, a JavaScript feature that has been available since Netscape 3. A rollover button is a button that becomes active when the user positions the mouse over it. The button also can have a special activation state when it is pressed. To create a rollover button, you first will need at least two, perhaps even three images, to represent each of the button's states ”inactive, active, and unavailable. A sample set of rollover images is shown here:

click to expand

To add this rollover image to the page, simply use the <img> tag like another image. The idea is to swap the image out when the mouse passes over the image and switch back to the original image when the mouse leaves the image. By literally swapping the value of the src attribute when the mouse is over the image, you can achieve the rollover effect. Assuming you have two images, buttonon.gif and buttonoff.gif, this in essence is what the following script, which should work in nearly any browser, would do:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Rollover Script  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   <script type="text/javascript">  <!-- /* check to ensure rollovers are supported in browser */ if (document.images)  {  /* preload the images */  buttonoff = new Image();  buttonoff.src = "buttonoff.gif";  buttonon = new Image();  buttonon.src = "buttonon.gif"; }         /* function to set image to on state */ function On(imageName) {  if (document.images)    {     document[imageName].src = eval(imageName+"on.src");   } }         /* function to reset image back to off state */ function Off(imageName) {  if (document.images)    {     document[imageName].src = eval(imageName+"off.src");    } } //-->  </script>   </head>   <body>   <h1 align="center">  Rollover Fun  </h1>   <hr />   <a href="http://www.democompany.com" onmouseover="On('button');"   onmouseout = "Off('button');">   <img src="buttonoff.gif" alt="DemoCompany" name="button"   width="90" height="20" border="0" /></a>   </body>   </html>  

Let's take a look at how the code works. The first section of the JavaScript checks to make sure the browser supports the images part of the document object model. This capability is required if rollover buttons are to work. If the browser supports this feature, the images are loaded in and assigned names . Once the page is loaded, the user can move the mouse over the image. The link, as indicated by the <a> tag, has two event handlers: one for the mouse passing over the image ( onmouseover ) and one for the mouse leaving the image ( onmouseout ). These handlers call our defined On() and Off() JavaScript functions, respectively. The function On() simply sets the src of the <img> tag to the name of the image passed to it and appends on.src , which changes the image to the on state. The function Off() does the opposite by setting the src equal to the image name with off.src appended to it. The key to adding more rollover images is adjusting their names carefully . For example, if you wanted to add another button called button1.gif , you add the following code to the <script> tag within the first if statement:

 button1off = new Image(); button1off.src = "button1off.gif"; button1on = new Image(); buttonon1.src = "button1on.gif"; 

and the following code later on in the document:

  <a href="URL to load " onmouseover="On('button1')"   onmouseout = "Off('button1')">   <img src="buttonoff1.gif" alt="button 1" name="button1" width="90"   height="20" border="0" /></a>  

Of course, the URL height, width, and even image name can vary from rollover image to rollover image. Make especially sure to name objects uniquely and consistently and set the name attribute for the <img> tag properly. Because rollovers are so common on Web sites, there are many sites, such as http://www.webreference.com/js, that offer rollover tutorials. Tools such as Macromedia's Dreamweaver also can create the code instantly when provided with two images.

Tip  

Given the penalty of downloading multiple images, it is a good idea to phase out JavaScript- based image rollovers for light-weight CSS text rollovers using the :hover pseudo property discussed in Chapters 10 and 11.

Form Validation

Form validation, the final example of script usage, probably is the most important use of scripting on the Web. Interestingly enough, it was the original reason JavaScript was developed. JavaScript form validation is the process of checking the validity of user-supplied data in an XHTML form before it is submitted to a server-side program such as a CGI program. By checking data before it is sent to a server, you can avoid a lot of user frustration, and reduce communication time between the Web browser and the server.

Because it is easy enough in JavaScript to look at a field's value, suppose that you want to make sure that the user enters something in the field before submitting a form. Consider the example here, which looks at the contents of a field and makes sure it isn't blank before allowing submission:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Overly Simple Form Validation  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   <script type="text/javascript">   <!--  function validate()  {   if (document.myform.username.value == "")    {     alert('Please enter your name');     return false;    }   else    return true;  } // -->  </script>   </head>   <body>   <form name="myform" id="myform" action="http://www.htmlref.com"   method="get" onsubmit="return validate();">   <b>  Name:  </b>   <input type="text" name="username" id="username"   size="25" maxlength="25" />   <br /><br />   <input type="submit" value="Submit" />   </form>   </body>   </html>  

In this example, the function validate() is called and the contents of the field username is checked to see whether it is blank or contains information. If the field is left blank when the user clicks the button, the user is told to complete the field and a false value is returned. Otherwise, a return value of true is set and the submission is allowed to continue. The return value is related to the call via the HTML event handler attribute onsubmit , which is triggered when the user clicks the Submit button. The submission will occur unless the event returns a false value. Notice how the validation function validate() returns a true or false value, based upon the user's input. Expanding this example to check more fields is not difficult.

The next example can be configured to check arbitrary fields for blank entries, valid e-mail addresses, or numeric only values. At the start of the script that follows , notice the validations[ ] array. To modify the script, just set the value of the array entries to the name of your fields and a validation string of either notblank , validemail , or isnumber . So, if you had a field named myAge in a form named form1, you would use

 validations[0] = ["document.form1.myAge", "isnumber"]; 

For every field in your form, you would increment the value in the validations[ ] array and add a new value pair consisting of the object path to the field to check the validation string.

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Form Check  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   <script type="text/javascript">  <!-- var whitespace = " \t\n\r"; /* Define validations to run */     validations = new Array(); validations[0] = ["document.myform.username", "notblank"]; validations[1] = ["document.myform.useremail", "validemail"]; validations[2] = ["document.myform.favoritenumber", "isnumber"]; function isEmpty(s) {    var i;    if((s == null)  (s.length == 0))      return true;    // Search string looking for characters that are not whitespace     for (i = 0; i < s.length; i++)     {            var c = s.charAt(i);         if (whitespace.indexOf(c) == -1)                return false;     }     // All characters are whitespace.     return true; }     function isEmail(field) {    var positionOfAt;   var s = field.value;   if (isEmpty(s))    {        alert("Email may not be empty");        field.focus();        return false;    }   positionOfAt = s.indexOf('@',1);     if ((positionOfAt == -1)  (positionOfAt == (s.length-1)))    {     alert("E-mail not in valid form!");     field.focus();     return false;    }    return true; }     function isDigit(c) {     return ((c >= "0") && (c <= "9")) }     function isInteger(field) {    var i, c;   var s = field.value;   if (isEmpty(s))    {     alert("Field cannot be empty");     field.focus();      return false;    }  for (i = 0; i < s.length; i++)   { // Check if current character is number.    c = s.charAt(i);    if (!isDigit(c))      {       alert("Field must contain only digits");       field.focus();       return false;     }   }    return true; }     function validate() {  var i;  var checkToMake;  var field;      for (i = 0; i < validations.length; i++)    {      checkToMake = validations[i][1];      field = eval(validations[i][0]);       switch (checkToMake)       {        case 'notblank': if (isEmpty(field.value))                           {                            alert("Field may not be empty");                             field.focus();                            return false;                           }                          break;          case 'validemail' : if (!isEmail(field))                                return false;                                break;          case 'isnumber' : if (!isInteger(field))                              return false;        }   }       return true; } //-->  </script>   </head>   <body>   <form name="myform" id="myform" method="get"   action="http://www.htmlref.com"   onsubmit="return validate();">  Username:  <input type="text" name="username" id="username" size="30" />   <br />  Email:  <input type="text" name="useremail" id="useremail" size="30"   maxlength="30" /><br />  Favorite number:  <input type="text" name="favoritenumber"   id="favoritenumber" size="10" maxlength="10" /><br />   <input type="submit" value="Submit" />   </form>   </body>   </html>  

The previous discussion is meant to serve only as a basic introduction to form validation. It is easy enough to add more fields to the example and even check for other types of data. However, even if you are an experienced programmer, it is not suggested that you go out and attempt to create your own validation scripts for e-mail addresses, credit card numbers , zip codes, and so on. Many libraries already exist that perform these tasks ; these libraries are available from JavaScript archive sites as well as from Netscape's original form validation library, located at http://developer.netscape.com/docs/examples/javascript/formval/overview.html.



 <  Day Day Up  >  


HTML & XHTML
HTML & XHTML: The Complete Reference (Osborne Complete Reference Series)
ISBN: 007222942X
EAN: 2147483647
Year: 2003
Pages: 252
Authors: Thomas Powell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net