Benjamin Tinker Team : Web Development Tags : Web Development

Optimise your jQuery

Benjamin Tinker Team : Web Development Tags : Web Development

There are many jQuery plugins out there that allow for dropdown menus to work. There are too many to choose from and here are 38 as an example.

During development I like to set up my CSS and pages prior to having to include 3rd party software to make functionality work. This ensures that my layouts are correct and I can produce some clean code that does what I require and only what I require. Yet when including a jQuery plug-in they always come with lots and lots of their own CSS which can be a nightmare at best to retro-fit to your standards. So, why not just dump the 3rd party plug-in and develop a function that does all you want like this one;

function setTopNav() {
var tabs = $('.topnav ul.topnavroot > li');

//find those without nosub
var subtabs = tabs.not('.nosub');

//bind hover event
subtabs.each(function () {
$(this).hover(
function () { $(this).find('.dropdown').show(); },
function () { $(this).find('.dropdown').hide(); }
);
});
}

The benefit of this is that it only attaches dropdown actions to those navigation items that actually have a dropdown menu. My mark-up tags each navigation item with a ‘.nosub’ for ease of finding them. I know I could have done another query to find those without sub menus but for ease I just reduced it to one line. The rest just binds my hover action to those navigation items i want the dropdown to work on. Simple, concise and it works in all browsers.