Home > Articles > Open Source > Ajax & JavaScript

JavaScript for Navigation

This chapter is from the book

In This Chapter

  • Project I: JavaScript and Pull-Down Menus—Getting to Where You Want to Go!

  • Project II: Using Multiple Pull-Down Menus for Navigation

  • Project III: Using JavaScript on a Log-in Page

  • Project IV: Using CSS/DHTML with JavaScript for Navigation

  • Recap

  • Advanced Projects

So far, you have done a great job adding some new functionality and pizzazz to Shelley Biotech's homepage. Now that your boss has seen how great JavaScript can be, another idea has popped into his head. The powers that be would love to be able to add a pull-down menu to the secondary navigation on the site that would let the user jump quickly to certain pages that are several levels down in the site with only a single click. Of course, like most of your projects, they need it done ASAP, so it's off we go on another "learn while you go" assignment.

After meeting with one of the designers, you feel that you have worked out a good place to put the pull-down menu on the homepage (see Figure 3-1). Now you just need to get the links that they want you to populate the pull-down with. An email to your boss takes care of that easily enough, and you're soon ready to go.

03fig01.jpgFigure 3-1. Pull-down menu added to the secondary navigation.


Project I: JavaScript and Pull-Down Menus—Getting to Where You Want to Go!

The first thing we need to do is insert the HTML code into the secondary navigation that will give us our pull-down menu and Go button. Here is the code that we will use.

<select name="PullDown">
     <option value=" ">Get There Quick
     <option value=" ">What's New
     <option value=" ">Featured Product
     <option value=" ">Press Releases
     <option value=" ">Company Store
</select>
<input type="button" name="Go" value="Go">

Because we will be inserting the pull-down into a preexisting design, we will place the <FORM> tag, which will be named NavForm, at the beginning and end of the HTML body instead of directly around the form element to prevent any unwanted line breaks or spaces. You will also notice that the value properties of the options are left blank; we will fill those in later when we insert the event handler needed to run the script.

Creating the Navigation Function

As the pull-down navigation is going to be on every page in the site, we place the function that will run it in our external JavaScript file right below the Product Banner Randomizer functions, like so.

setTimeout("bannerChanger()", 20000);


// Pull-Down Menu Navigation Function
function PageChanger(page) {
   . . .
}

The function itself will be fairly simple and will consist of only two parts. Notice that we pass a value into the function that is assigned to the variable page. This value will be the location of the page that the user has selected from the pull-down menu. In the first line, we use that value to change the location property of the DOCUMENT object; this reloads the browser window with the new Web page.

 // Pull-Down Menu Navigation Function
function PageChanger(page) {
     document.location= page;
     . . .
}

Next, we add a line that serves a housekeeping function more than anything else. When the function is run, this line resets the pull-down menu to the first choice in the menu. This is helpful if the user uses the Back button to return to this page. If we didn't put this line in, on some browsers the last selection the user made in the pull-down would still be visible.

// Pull-Down Menu Navigation Function
function PageChanger(page) {
     document.location= page;
     document.NavForm.PullDown.options[0].selected=true;
}

Inserting the Event Handler

Now that we have created our function, we need to insert the event handler into our HTML to call the function. Before we do that, let's insert the value properties into the pull-down menu's options. As stated earlier, the value that we pass into our function is the URL for the page we want to send the user to. This value comes from the VALUE attribute of our menu options. Therefore, for the value of each option, we need to put the location of the page for that selection.

<select name="PullDown">
     <option value="">Get There Quick
     <option value="whatsnew.html">What's New
     <option value="featured_product.html">Featured Product
     <option value="press.html">Press Releases
     <option value="store.html">Company Store
</select>

For the first menu option, which is just a title put there for aesthetic purposes, we don't put in a value because we don't want that option to send the user anywhere. Once the user selects the desired menu option, he or she needs to click on the Go button to get there. To trigger this, we need to insert an onClick handler into the HTML for the Go button.

<select name="PullDown">
     <option value="">Get There Quick
     <option value="whatsnew.html">What's New
     <option value="featured_product.html">Featured Product
     <option value="press.html">Press Releases
     <option value="store.html">Company Store
</select>

<input type="button" name="Go" value="Go" onClick="PageChanger(document.NavForm.PullDown
graphics/ccc.gif.options [NavForm.PullDown.selectedIndex].value)">
   

We do two things in the event handler: We call the PageChanger() function and we pass a value to it. The value that we pass is the value of the option that the user has chosen from the pull-down menu. In the functions we have created so far, the value that we have passed into the function has been a simple string. In this event handler, we are trying something new: We are referencing the pull-down menu object that has been selected and accessing its value. This value is then passed into the function and used to send the user to the page he or she wants.

Our script is now functional and ready to go. However, because of the Go button we added to the page, the categories to the right of the pull-down menu have been forced to take up two lines (Figure 3-2), which unfortunately isn't acceptable, so we need to find another way to do it. Luckily for us, there is another way we can power our script that will not only take care of this problem, but will make navigating with the pull-down menu even faster.

03fig02.jpgFigure 3-2. Page with pull-down menu and Go button.


Using onChange for Instant Gratification

To get the page layout back to its original state, we need to get rid of the Go button; however, at the moment, it contains the event handler that triggers our script. What we need is a handler that we can put into the pull-down menu itself to run our script for us. Fortunately, just such a handler exists, the onChange event handler. This handler looks for a change in the state of the object that it is contained within, and when it finds one, it triggers.

By inserting it in our pull-down menu, we can have it activate our function when the user changes the menu option from the default option that is loaded with the page. Let's see how this changes our HTML code.

<select name="PullDown" onChange="PageChanger(this.options[this.selectedIndex] .value)">
     <option value=" ">Get There Quick
     <option value="whatsnew.html">What's New
     <option value="featured_product.html">Featured Product
     <option value="press.html">Press Releases
     <option value="store.html">Company Store
</select>

First, notice that we have removed the Go button, as it is no longer needed. Second, the onChange event handler has been added to the pull-down menu. The value we pass to the function is the same: the value of the option the user has selected. However, we call that value differently than the way we called it before. Because the event handler is in the form element that we wish to get the value from, we can use the following method.

this.options[this.selectedIndex].value

Instead of calling the specific form element by name, we tell it to "grab the requested information from the form element that contains this handler." Both methods work equally well, and it's always good to be exposed to multiple ways of accomplishing a task.

With the insertion of the new event handler, our script is finished and ready to work. With the onChange handler, the page now changes as soon as the user makes a choice from the menu, without having to press a button.

Reviewing the Script

Let's look at what we did to create this script. We first created a function that accepts a value from a form element and uses it to send the user to another HTML page. We also went over two different event handlers that can be used to drive the scripts.

First, let's look at the function.

// Pull-Down Menu Navigation Function
function PageChanger(page) {
     document.location= page;
     document.NavForm.PullDown.options[0].selected=true;
}
  1. We created the function PageChanger().

  2. We set the location property of the DOCUMENT object to the value contained within the variable page. This value is the URL that is being passed into the function from the pull-down menu.

  3. We reset the option that shows in the pull-down menu to the first option.

Now let's look at the HTML needed for use with the onClick handler.

<select name="PullDown">
     <option value="">Get There Quick
     <option value="whatsnew.html">What's New
     <option value="featured_product.html">Featured Product
     <option value="press.html">Press Releases
     <option value="store.html">Company Store
</select>

<input type="button" name="Go" value="Go" onClick="PageChanger(document.NavForm.PullDown
graphics/ccc.gif.options [NavForm.PullDown.selectedIndex].value)">
   
  1. Our function is called when the user clicks on the Go button. We inserted the onClick event handler into the button form element.

  2. Within the event handler, we call our PageChanger() function and pass into it the value held by the menu option that has been chosen from the pull-down menu.

  3. Once we decided to take the Go button off the page because of design issues, we used the onChange event handler instead.

    <select name="PullDown" onChange="PageChanger(this.options[this.selectedIndex] .value)">
         <option value=" ">Get There Quick
         <option value="whatsnew.html">What's New
         <option value="featured_product.html">Featured Product
         <option value="press.html">Press Releases
         <option value="store.html">Company Store
    </select>
    
  4. We inserted the onChange event handler into our pull-down menu. Again within this event handler, we call our PageChanger() function and pass into it the URL of the selected menu option.

Let's take a look at the new concepts that we have covered during this project.

  • We learned how to access and change the location property of the DOCUMENT object.

  • We learned how to access the values of pull-down menu options and how to change which option is currently selected within a pull-down menu.

  • We were introduced to two new event handlers, onClick and onChange.

As Web sites become more and more important to the success of companies, the amount of content contained in them grows by leaps and bounds. Finding quick and efficient methods to navigate the information is now more important than ever. The two methods just discussed are definitely useful.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020