Apr 062013
 
Article Javascript

A fancy way to display a list of items structured in categories and sub-categories, is by means of a drop-down list. The user can choose to expand an examine only the content of categories and sub-categories that interest him/her.

This post explains a method to implement this functionality using HTML, CSS and javascript.

The resulting drop-down list

Below is a sample of the kind of expandable list that can be generated following the procedure explained in this post:

Points of interest in Córdoba

  • Tourism
    • Attractions
      • Palacio de Moret
      • plaza de toros
      • Alcázar de los Reyes Cristianos
      • Calleja del Pañuelo
      • Baños árabes - Hamman
      • Tren del Aceite
  • Transport
    • 60 Parkings
    • 13 Paradas de autobús
    • 622 Estaciones de gasolina
    • 5 Estaciones de autobuses
      • Estación central de Osuna
      • Estación de Autobuses (Cabra)
      • Estación de Autobuses (Lucena)
      • Estación de Autobuses (Lucena)
      • Estación de Autobuses (Cabra)
    • 16 Paradas de taxi

 

The HTML code

The HTML code of the list is a hierarchical structure of elements, created using the html tags <ul> and <li>:

  • Every item in the list is enclosed in tags <li>…</li>
  • A group of items is enclosed in tags <ul>…</ul>
  • An item in the list can include a subgroup, in a hierarchical structure of two or more levels.

The topmost group is identified adding the attribute id=”expList” to the <ul> tag

Items in the list that include subgroups are indentified as well, adding the attribute class=”expandIcon” to the <li> tag

The javascript code

The javascript code used in the implementation makes use of the jQuery library.

In the jQuery initialization code, a call to “prepareLlist()” is added.

This function identifies all the <li> elements that are descendant of the <ul> element identified with the id “expList”, and also include <ul> subgroups, and assigns an “onclick” event handler to them.

The onclick handler toggles the visibility of <ul> groups that are children of the clicked-on item. It also adds or removes from the item the “el_expanded” class. This class determines the icon displayed to the right of the item (in the sample above, a “+” sign if the list is contracted, or else a “-” sign if it is expanded).

The CSS code

Finally, some CSS code is used to specify the style of the list items

In the sample, this CSS code is used:

 Posted by at 11:25 am

 Leave a Reply

(required)

(required)