Example HTML (for the sake of clarity):
<nav>
<ul>
<li class="top-navbar-channels">
<a href="#"></a>
<div class="dropdown-menu">BLAH, BLAH, BLAH!</div>
</li>
<li class="top-navbar-about">
<a href="#"></a>
<div class="dropdown-menu-about">BLAH, BLAH, BLAH!</div>
</li>
<li class="top-navbar-search">
<a href="#"></a>
<div class="dropdown-menu-search">BLAH, BLAH, BLAH!</div>
</li>
</ul>
</nav>
Example jQuery code:
jQuery(document).ready(function($){
$('.dropdown-menu').on('show', function () {
$('.top-navbar-channels > a').addClass('selected');
});
$('.dropdown-menu').on('hide', function () {
$('.top-navbar-channels > a').removeClass('selected');
});
$('.dropdown-menu-about').on('show', function () {
$('.top-navbar-about > a').addClass('selected');
});
$('.dropdown-menu-about').on('hide', function () {
$('.top-navbar-about > a').removeClass('selected');
});
$('.dropdown-menu-search').on('show', function () {
$('.top-navbar-search > a').addClass('selected');
});
$('.dropdown-menu-search').on('hide', function () {
$('.top-navbar-search > a').removeClass('selected');
});
});
For those who are curious… the jQuery code adds a new class selected to the active menu item’s link. In my case it’s Twitter Bootstrap-based collapsible menu, where active means, the menu item is not collapsed i.e. open.
Now, the question is, can the jQuery code be optimized (i.e. same functionality with less code)? If so, how?
Add a common class to common main elements so you can use that single class as the selector. You can also combine the events into one
on()call and usetoggleClass()on the link.on()allows for multiple space separated eventsExample
Then for jQuery: