Lists are a very simple, but very effective, way of displaying information on a web page and, rather than having a static list, the web programmer can create a dynamic list - just by adding an empty list and a little Javascript code.
Adding an Empty List to a Web Page
Web page lists come in two formats:
- ordered lists
- unordered lists
and the HTML code to create either kind of list is very similar; the code to create an empty ordered list is:
and the code to create an empty unordered list is:
The Javascript code to populate the lists will work with either type of list - but a unique id must be assigned to the list, for example:
The next step is to write the code that will add the items to the list.
Using Javascript to Add Items to a List
The code for the list creation will:
- add individual items to a list
- clear a list
- populate a list from an array
And for this three Javascript functions will be required.
Adding a Single Item to a List
The function for adding an item to a list requires the id of the list and some text as an input - it then appends a new LI object to the list (which is itself another object on the web page):
This could be run with the following Javascript code:
and that would add a single item to the empty list.
Populating a List from an Array
Rather than adding the items one by one it may be more efficient to load the items from an array - this next function takes an array as an input and loops through it, adding items to the list using the function above:
An array is required in order to run this, for example:
This time two items would be added to the list.
Clearing a List
Since the list is to be dynamic it will have to be cleared before a new list is created - this next function loops, deleting items until there are no items left:
and it would run by adding the Javascript code:
That's all the functionality that's required to make a list dynamic - however, some more code is required that will make the changes actually happen.
Using a Select Box to Change a List
In this example a change in the selection of a drop-down list box (or combo-box) will cause the list to be updated - therefore a suitable drop-down list box is required:
The list is to be updated whenever the selection in the combo-box changes - therefore a function has to be assigned to the box's onchange event:
Finally the subroutine is required that will load the appropriate list according to the selection made in the drop-down list box:
Now the list will now change whenever the web page user changes the selection in the combo-box.
Further Reading
For further information on creating web page lists read How to Create Lists on a Web Page.