Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Last active August 29, 2015 14:18
Show Gist options
  • Save DroopyTersen/7c72aa679c1d63e8ea3d to your computer and use it in GitHub Desktop.
Save DroopyTersen/7c72aa679c1d63e8ea3d to your computer and use it in GitHub Desktop.
Parses SP2010 top menu markup and returns a simplified menu object that outputs clean html
var spMenuSpider = (function($) {
var menu = [];
var MenuLink = function (name, url) {
this.name = name || "",
this.url = url || "#",
this.children = [];
};
MenuLink.prototype.toHtml = function() {
var html = "<li class='menuitem'>";
html += "<a class='menulink' href='" + this.url + "'>" + this.name + "</a></li>"
if (this.children.length) {
html += "<li><ul class='submenu'>";
for (var i = 0; i < this.children.length; i++) {
html += this.children[i].toHtml();
}
html += "</ul></li>";
}
return html;
}
var toHtml = function() {
var html = "<ul class='cleanmenu'>"
for (var i = 0; i < menu.length; i++) {
html += menu[i].toHtml();
}
html += "</ul>";
return html;
};
var getMenu = function() {
menu = [];
var $root = $(".s4-toplinks ul.root");
$root.find(".static.menu-item").each(function(){
var $this = $(this);
var link = new MenuLink($this.text(), $this.attr("href"));
if ($this.closest("li").hasClass("dynamic-children")) {
link.children = getSubMenuLinks($this.closest("li").find("ul.dynamic"));
}
menu.push(link);
});
menu.toHtml = toHtml;
return menu;
};
var getSubMenuLinks = function($ul) {
var children = [];
$ul.find(".dynamic.menu-item").each(function(){
$this = $(this);
var link = new MenuLink($this.text(), $this.attr("href"));
children.push(link);
});
return children;
};
return {
getMenu: getMenu
};
})(jQuery);
<ul class='cleanmenu'>
<li class='menuitem'><a class='menulink' href='/SitePages/Home.aspx'>Root</a></li>
<li class='menuitem'><a class='menulink' href='/clients'>Clients</a></li>
<li>
<ul class='submenu'>
<li class='menuitem'><a class='menulink' href='/clients/manitowoc'>Manitowoc</a></li>
</ul>
</li>
<li class='menuitem'><a class='menulink' href='http://google.com'>HeadingNoChildrenNoLink</a></li>
<li class='menuitem'><a class='menulink' href='http://google.com'>Heading with Link but no children</a></li>
<li class='menuitem'><a class='menulink' href='http://google.com'>Heading 1</a></li>
<li>
<ul class='submenu'>
<li class='menuitem'><a class='menulink' href='http://google.com'>Child Link</a></li>
<li class='menuitem'><a class='menulink' href='http://my.skylinetechnologies.com'>Child Link 2</a></li>
</ul>
</li>
</ul>
var menu = spMenuSpider.getMenu();
//Assume we had an empty div in the masterpage with a class of mobile menu
//Shove the clean menu html (see the example output) into the empty div
$(".mobile-menu").html(menu.toHtml());
//In this example we'd use media queries to hide the normal top nav and show 'mobile-menu' if the user is on a phone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment