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.
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.
This JSON 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.
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
It comprises two functions:
- 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).
- Starts by the call of the eval() function which transforms the textual
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.
This script workss as well on a local computer without server.
The demonstration: Build a Menu From a JSON File
The demonstration displays the menu automatically at start.
This demonstration displays a menu which is defined in the following JSON file: