Dynamic menu with JSON

♠ Posted by Unknown in at 01:07
This component allows you to load a list of pages you have created on your future website and build a menu from there.
Later we will give it a slightly more elegant design, with a style sheet, but for now it is enough to add a new brick to our CMS. We just need to add a line to JSON file when a new page is created to complement the menu.

Ajax

This is an Ajax script, which has the advantage of freeing us from any server side programming language. A simple Ajax function to create the XHR object.

The JSON file

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

The menu script

This script is included in the head section of the demo page, and called for charging it by the onload event:


window.onload=loadJSON
It has two functions:

loadJSON
It calls the XHR object creation function and load the file in responseTxt attribute. The content of the latter is then given parameter of the function called by buildMenu callback (its name is an argument of the loadJSON function).
BuildMenu
It starts by calling the eval () function that converts the text file given as an argument in JavaScript object.
Then the object is traversed iteratively (it could be recursively if we wanted to have sub-menus).
The storage tag is found by the function DOM getElementByID and added to its contents the next menu item by assigning it to the innerHTML attribute.
This script runs on a local computer without a server.

Demonstration

This demonstration displays a menu that is defined in the JSON file dynamic-menu.json.

Thanks to menu.js JavaScript that is tied in the head section of this page.

This is an Ajax script, it uses the function defined in the file ajax.js.

The lines below are generated by the script:


0 comments:

Post a Comment