ExpressionEngine, Structure and Bootstrap Navbar
Using the ExpressionEngine Structure module with bootstrap navbar and custom code.
Two agencies that I regularly do ExpressionEngine work require that the Structure Module is used in the builds. I've become quite proficient with Structure, but still prefer to build sites without it and do so when I have the option.
One of the issues I have with Structure is that the navigation tag is difficult to work with especially if you are using a framework such as Foundation or Bootstrap when building your sites. The structure nav tag doesn't allow for the customization of the HTML that is needed when using Bootstrap or Foundation. What I've done in the past is hard code the main nav items and use multiple Structure nav tags for the dropdowns. It works but isn't very efficient.
By adding a little javascript I can now use a single structure nav tag, have working dropdowns and allow the client to reorder the navigation at will.
My Navbar HTML looks like this:
<div class="navbar-wrapper">
<div class="container">
<div class="navbar navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Site Name</a>
</div>
<div class="navbar-collapse collapse">
{exp:structure:nav
start_from ="/"
current_class="active"
max_depth="3"
show_depth="3"
css_class="nav navbar-nav navbar-right"
}
</div>
</div>
</div>
</div>
</div>
All we need is a little jquery to get this to work correctly.
// make structure play nice with bootstrap dropdown navs
$( document ).ready(function() {
//add dropdown class if li contains ul and data-toggle to link
$('.navbar ul.navbar-nav li:has(ul)').addClass('dropdown').find('> a').addClass('dropdown-toggle').attr('data-toggle', 'dropdown');
//add dropdown-menu to nested ul
$('.navbar ul.navbar-nav li > ul').addClass('dropdown-menu');
});