Monthly Archives: August 2017

Setting the Active Navbar item with Bootstrap 4 and jQuery

Following in the footsteps of the fine answer at StackOverflow for “How to extract class from body element using jQuery?” using regular expressions, if you are adding your navbar as an include (following DRY principles), here is a nice clean way to not only automatically enable the active item in the navbar and its submenu, but also append the <span class="sr-only">(current)</span> for screenreaders, to the appropriate link text.

Now, all you need to do is on each page, add a ‘page-*‘ class to the <body> tag, which will connect with a matching class that you add on your .nav-item or .dropdown-item, like so (observe the highlighted lines):

Notice how, in the dropdown markup above, the individual dropdown items get one class each, but the nav-item containing it gets each of them appended, so that both the top level nav gets highlighted as active, as well as its entry in the submenu

Bootstrap 4 Beta navbar with active dropdowns set via jquery

Now that’s slick. Check it out on Codeply