Recursively print a menu in JavaScript

Dynamically print a menu using recursive JavaScript method call.

<html>
<head>
<title>Dynamic Menu - codesstore.blogspot.com</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript">
  
var menuItems = {
    "menu-0": {
        "id": "menu-0",
        "title": "Home",
        "parentId": null,
        "childCount": 0
    },
    "menu-1": {
        "id": "menu-1",
        "title": "About",
        "parentId": null,
        "childCount": 2
    },
    "menu-3": {
        "id": "menu-3",
        "title": "About Sub1",
        "parentId": "menu-1",
        "childCount": 2
    },
    "menu-5": {
        "id": "menu-5",
        "title": "About Sub2",
        "parentId": "menu-1",
        "childCount": 0
    },
    "menu-4": {
        "id": "menu-4",
        "title": "About Sub1 sub1",
        "parentId": "menu-3",
        "childCount": 0
    },
    "menu-6": {
        "id": "menu-6",
        "title": "Contact",
        "parentId": null,
        "childCount": 2
    },
    "menu-7": {
        "id": "menu-7",
        "title": "Contact sub1",
        "parentId": "menu-6",
        "childCount": 0
    },
    "menu-8": {
        "id": "menu-8",
        "title": "Contact sub2",
        "parentId": "menu-6",
        "childCount": 1
    },
    "menu-9": {
        "id": "menu-9",
        "title": "Contact sub2 sub1",
        "parentId": "menu-8",
        "childCount": 0
    },
 "menu-10": {
        "id": "menu-10",
        "title": "About Sub1 sub2",
        "parentId": "menu-3",
        "childCount": 2
    },
 "menu-11": {
        "id": "menu-11",
        "title": "About Sub1 sub2 sub1",
        "parentId": "menu-10",
        "childCount": 0
    }
 ,
 "menu-12": {
        "id": "menu-11",
        "title": "About Sub1 sub2 sub2",
        "parentId": "menu-10",
        "childCount": 0
    }
};



$(document).ready(function () {

    var htmlTxt = "";
    var cat = [];
    var htmlStrTxt = "";


    function recurseMenu(parent, level) {
        htmlStrTxt = '<ul>';
        for (var x in menuItems) {
            if (menuItems[x].parentId == parent) {
                htmlStrTxt += '<li><span class="level-' + level + '">' + menuItems[x].title + '</span>';
               
                if (menuItems[x].childCount > 0) {
                    htmlStrTxt += recurseMenu(menuItems[x].id, level + 1);
                }
                htmlStrTxt += '</li>';
            }
        }
        return htmlStrTxt + '</ul>';
    }

    var htmlTxt = recurseMenu(null, 0);
    $("#menu").html(htmlTxt);


});

</script>
</head>
<body>

<div id="menu">
 </div>
</body>
</html>

Output:

2 comments: