JavaScript navigation lists

We firstly need to create the list that the user can select an item from.

<select name="navigation" id="navigation" onchange="nav(this);">
   <option value="#">Select an Item</option>
   <option value="page1.html">Item1</option>
   <option value="page2.html">Item2</option>
   <option value="http://www.othersite.com/page3.html">Item3</option>
</select>

Note that the value of each item is the page to redirect to. The onchange event handler has been used to call the function nav with a reference to itself.

The nav function

This is a simple function that gets the selected item from the list and changes the location of the window to the value of the item.

function nav(list)
{
   location.href = list.options[list.selectedIndex].value;
}

The code above assumes that you have made the list in HTML and it will not change. The following code will allow the list to be built dynamically at run time.

<select name="navigation" id="navigation" onchange="nav(this);">
</select>

This is the empty list that we will fill up dynamically.

var option = new Array();
option[0] = new Array('#','Select an option');
option[1] = new Array('page1.html','Page 1');
option[2] = new Array('page2.html','Page 2');
option[3] = new Array('page3.html','Page 3');

Here we define the list items we would like to add.

Creating the list

We finally need to make the list from the array.

function make_list()
{
   var fragment = document.createDocumentFragment();
   var list = document.getElementById('navigation');
   for(i=0;i < option.length;i++)
   {
      var new_option = document.createElement('option');
      var text = document.createTextNode(option[i][1]);
      new_option.appendChild(text);
      new_option.setAttribute('value',option[i][0]);
      fragment.appendChild(new_option);
   }
   list.appendChild(fragment);
}

This code used the DOM model to add the list items from the array. Finally we need to initialise the function when the page loads.

<body onload="make_list();">

Categories

Tags

No tags

Social