In this tutorial I’ll show you how to create a superb clickable drop-down navigation, using jQuery and of course complete with CSS fallbacks. These types of drop-downs are great for Web Apps, websites and backends which you don’t want to implement a hover-only system.
It’s all about the user experience and journey around the site. Here I’ll show you how to create a really smart clickable drop-down navigation, in which you can click any negative space to close it again.
Full browser support, Chrome, FireFox, Safari, Opera, IE7, IE8, IE9. The function executes perfectly in IE6 too.
We’ll be using a markup similar to the way a drop-down menu navigation works, an unordered list, with a list inside, with an unordered list containing our items inside the drop-down.
Here’s the markup:
Let’s go through the structure.
We start with a div with the class click-nav, this is required for two reasons, to make it easier for you to position in your website as the drop-down has a wrap, and more importantly, our jQuery is going to use it as a hook for our animating.
The first menu item is what will be our clickable element, aptly named clicker, with our small icon and text inside. Inside the same element, we have our unordered list, which will be the drop-down list of items.
The CSS is minimal here, a great foundation for customising. No messy background images either, keeping it clean. Our click-nav class controls the width of the drop-down. Our .click-nav ul li is positioned relative, to allow the the absolute positioning for the ul nested inside. I’ve used left:0;right:0; here, so that it fills the entire width of the drop-down without adjusting anymore widths. An active class has also been included, for styling purposes when the navigation is clicked.
You’ll also see the fallbacks underneath, using a simple CSS hover to display our navigation. Accessibility is key.
Here’s where we get started with our clickable script.
Secondly, we hide our .js ul, the enabled items to hide them.
Then we get clever with our click event, using a slideToggle function alongside toggleClass to slideDown/slideUp our drop-down and addClass/removeClass active. The most integral part here is stopPropagation, which is similar to return false;, but using return false; would disable all links within our drop-down from being clicked on. This also prevents the full toggles to complete, allow for the second click the fire the second part of the toggle.
There are two ways to ‘close’ the drop-down. Simply click the button again to drop it down, and also to provide a better user experience, you can click absolutely anywhere inside the webpage to close it. You’ll see we’ve setup $(document) as our click object.