Skip to content

Instantly share code, notes, and snippets.

@jaymzcd
Last active August 29, 2015 13:57
Show Gist options
  • Save jaymzcd/9761402 to your computer and use it in GitHub Desktop.
Save jaymzcd/9761402 to your computer and use it in GitHub Desktop.
Quick and dirty menu using nested arrays to any level and recursion
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
var menu = [
{name: "item 1", link: "http://google.com"},
{name: "item 2", items: [
{name: "subitem1", link: "#" },
{name: "subitem2", link: "#" }
]},
{name: 'item 3', link: 'http://u-dox.com'},
{name: 'item 4', link: '#'},
{name: "item 5", items: [
{name: "subitem1", link: "#" },
{name: "subitem2", link: "#" },
{name: "subsub menu!", items: [
{name: 'item 1', link: '#'},
{name: 'item 2', link: '#'},
{name: 'item 3', link: '#'},
{name: 'item 4', link: '#'}
]}
]},
]
function render_menu(menu) {
var out = '<ul>';
for(var i=0; i<menu.length; i++) {
if(menu[i].items !== undefined) {
out += render_menu(menu[i].items);
} else {
out += '<li><a href="' + menu[i].link + '">' + menu[i].name + '</a></li>';
}
}
out += '</ul>';
return out;
}
$(document).ready(function() {
$('body').prepend(render_menu(menu));
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment