HTML and CSS Reference
In-Depth Information
h e names of the form and select elements are important because JavaScript uses the
names as a path to the selected option . (If you're familiar with arrays, the options are all
treated as array elements.)
h e JavaScript is placed in a separate i le because if you're going to be using it with a global
navigation system, you don't want to have to rewrite it with every page. h e following
JavaScript should be saved in a text i le named globMenu.js .
function optionMenu ()
{
var choice = document . menuNow . global1 . selectedIndex ;
var urlNow = document . menuNow . global1 . options [ choice ]. value ;
window . location . href = urlNow ;
}
What that rel ects is the HTML5 Document Object Model (DOM). h e document is the
Web page, menuNow is the name of the form element, global1 is the name of the select
element, and selectedIndex is the selected option. Because the selectedIndex is a
number between 0 and the number of options in the <select> tag container, it can be used
to choose the array element (option), which is selected. Whatever value is stored in the option
is passed to the variable named urlNow . For example, the following line has a relative URL of
animals/dogs.html :
< option value = ”animals/dogs.html” > Dogs </ option >
157
h e i nal line in the JavaScript, window.location.href = urlNow , has the same
function as the following HTML5 line:
< a href = ”animals/dogs.html” >
In this context, a dif erent JavaScript function would have to be written for each <select>
tag because the function uses a specii c reference to that tag ( global1 ). More sophisticated
JavaScript could be developed to use variables for the dif erent element names, but the
function employed here is relatively short and easier to implement.
To test this out yourself, create simple Web pages with the following names:
horses.html
dogs.html
cats.html
rabbits.html
raccoons.html
h e Web pages can just have names on them — nothing fancy. h en, in the same directory,
enter the following HTML5 code ( SelectNavJS.html in this chapter's folder at www.
wiley.com/go/smashinghtml5 ).
 
Search WWH ::




Custom Search