Dynamic Menu with JSON

This component makes it possible to load a list of pages which you have created on your Web site and to build a menu from there.
Futurely we will give him a little more elegant design, thanks to a style sheet, but for now, it is sufficient to add a new brick to our CMS. We have only to add a line to the JSON file when a new page is created, to complete the menu.

Ajax

It is an Ajax script, which has the advantage of deliver us from using any server side programming language. Thanks to a simple Ajax function, we have just to create the XHR object.

See the Ajax function.

The JSON File

This file, and it is the true interest of this dynamic menu, can be generated automatically by an application, in particular when a new article is created and that we want to add it to the summary.

See the JSON file.

The script of the menu

This script is included in the head section of the demonstration page, and executed at loading of it by the onload event

window.onload=loadJSON

It comprises two functions:

loadJSON

Calls the function of creation of XHR object and load the file in the responseTxt attribute. The contents of this one are then given in parameter to the buildMenu function called as callback (its name is an argument of the loadJSON function).

buildMenu

Starts by the call of the eval() function which transforms the textual file given as argument into JavaScript.
Then the object is traversed in an iterative way (it could be it in a recursive way if one want to use sub-menues).
The tag of storage is found by the getElementByID DOM function and one adds to his contents each next element of menu by assigning it to the innerHTML attribute.

See the script of menu.

This script workss as well on a local computer without server.

The demonstration

See the demonstration.

The demonstration displays the menu automatically at start.

More information

(c) 2007 Denis Sureau and Sandrine Takis. Scriptol.com
Licence: You are free to use the code of this tutorial to motorize your own site. Please do not put the tutors and other files on another website, add a link to the article instead. But you can print the pages and distribute them along with the code for educational purpose.