Mega Drop Down Menus with CSS & jQuery

Step 1. Foundation – HTML

Start by creating an unordered list. Since we will be using CSS Sprites for our navigation states, each link within the list item should have a unique class name to it.

<ul id="topnav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Products</a></li>
    <li><a href="#">Sale</a></li>
    <li><a href="#">Community</a></li>
    <li><a href="#">Store Locator</a></li>
</ul>

Step 2. Styling Foundation – CSS

Since our drop down menu will be using absolute positioning, be sure to add a relative positioning to the list item. Shoot the text off of the page by specifying a text-indent of -9999px. We will then replace each navigation link with an image by specifying an image path to each link class name.

ul#topnav {
	margin: 0; padding: 0;
	float:left;
	width: 100%;
	list-style: none;
	font-size: 1.1em;
}
ul#topnav li {
	float: left;
	margin: 0; padding: 0;
	position: relative; /*--Important--*/
}
ul#topnav li a {
	float: left;
	text-indent: -9999px; /*--Push text off of page--*/
	height: 44px;
}
ul#topnav li:hover a, ul#topnav li a:hover { background-position: left bottom; } /*--Hover State--*/
ul#topnav a.home {
	background: url(nav_home.png) no-repeat;
	width: 78px;
}
ul#topnav a.products {
	background: url(nav_products.png) no-repeat;
	width: 117px;
}
ul#topnav a.sale {
	background: url(nav_sale.png) no-repeat;
	width: 124px;
}
ul#topnav a.community {
	background: url(nav_community.png) no-repeat;
	width: 124px;
}
ul#topnav a.store {
	background: url(nav_store.png) no-repeat;
	width: 141px;
}

Step 3. Creating the Mega Sub Navigation – HTML

Add a class of “sub” right after your main navigation link and nest unordered lists within. Each nested unordered list will act as the nav columns of your mega drop down.
Mega Drop Down Menu

<ul id="topnav">
    <li><a href="#">Home</a></li>
    <li>
    	<a href="#">Products</a>
        <div>
            <ul>
                <li><h2><a href="#">Desktop</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Laptop</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Accessories</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Accessories</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
        </div>
    </li>
    <li><a href="#">Sale</a></li>
    <li><a href="#">Community</a></li>
    <li><a href="#">Store Locator</a></li>
</ul>

Step 4. Styling Mega Sub Navigation – CSS

To get the sub nav to stick to the bottom left corner of the parent hovered nav, be sure to set an absolute position to the .sub container with the coordinate of top 44px and left 0px. For style, I added rounded corners to those browsers that support it (Firefox/Chrome/Safari).

Keep in mind when having multiple levels of nested lists, you need to override its conflicting properties. Check out the comments below.

ul#topnav li .sub {
	position: absolute; /*--Important--*/
	top: 44px; left: 0;
	z-index: 99999;
	background: #344c00 url(sub_bg.png) repeat-x; /*--Background gradient--*/
	padding: 20px 20px 20px;
	float: left;
	/*--Bottom right rounded corner--*/
	-moz-border-radius-bottomright: 5px;
	-khtml-border-radius-bottomright: 5px;
	-webkit-border-bottom-right-radius: 5px;
	/*--Bottom left rounded corner--*/
	-moz-border-radius-bottomleft: 5px;
	-khtml-border-radius-bottomleft: 5px;
	-webkit-border-bottom-left-radius: 5px;
	display: none; /*--Hidden for those with js turned off--*/
}
ul#topnav li .row { /*--If needed to break out into rows--*/
	clear: both;
	float: left;
	width: 100%;
	margin-bottom: 10px;
}
ul#topnav li .sub ul{
	list-style: none;
	margin: 0; padding: 0;
	width: 150px;
	float: left;
}
ul#topnav .sub ul li {
	width: 100%; /*--Override parent list item--*/
	color: #fff;
}
ul#topnav .sub ul li h2 { /*--Sub nav heading style--*/
	padding: 0;  margin: 0;
	font-size: 1.3em;
	font-weight: normal;
}
ul#topnav .sub ul li h2 a { /*--Sub nav heading link style--*/
	padding: 5px 0;
	background-image: none;
	color: #e8e000;
}
ul#topnav .sub ul li a {
	float: none;
	text-indent: 0; /*--Override text-indent from parent list item--*/
	height: auto; /*--Override height from parent list item--*/
	background: url(navlist_arrow.png) no-repeat 5px 12px;
	padding: 7px 5px 7px 15px;
	display: block;
	text-decoration: none;
	color: #fff;
}
ul#topnav .sub ul li a:hover {
	color: #ddd;
	background-position: 5px 12px ;/*--Override background position--*/
}

Step 5. Setting up jQuery & Hover Intent

For those who are not familiar with jQuery, do check out their site first and get an overview of how it works. I’ve shared a few tricks that I have picked up along the way, you can check those out as well.

Initial Step – Call the jQuery file

You can choose to download the file from the jQuery site, or you can use this one hosted on Google.

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

After calling the jQuery file, visit and download the latest Hover Intent jQuery Plugin. Save the file to your current directory, and call the file.

<script type="text/javascript" src="jquery.hoverIntent.minified.js"></script>

Step 6. Launching Code on Document Ready

Directly after the line where you called your jQuery and hover intent file, start a new <script> tag and start your code by using the $(document).ready event. This allows your jQuery code to run the instant the DOM is ready to be manipulated. The code you will be writing in the next few steps will all take place within.

$(document).ready(function() {
	//Code goes here
});

Step 7. Set Hover Over & Hover Out Events – jQuery

Note: When using the hover intent plugin, it requires each hover over and hover out state to be in its own function.

The Logic

When a drop down parent link is hovered over:

  1. Find .sub and fade it in (By default, we will fade the opacity down to 0)
  2. Check if a .row exists (in case you want more than one row in the drop down)
  3. If .row does exists, find the widest row and set the width of the .sub container.
  4. If .row does not exist, set the width of the .sub container.

On hover out:

  1. Find .sub and fade it out (Opacity 0)
  2. Hide .sub (Display none – so it is completely out of the way)

The following script contains comments explaining which jQuery actions are being performed.

//On Hover Over
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width

    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
  });
}

Step 8. Set Custom Configurations & Trigger Function

Now that we declared the hover over and hover out function in the above step, its now time to set the custom configurations and call the hover intent function.

//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};

$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations

For more detailed explanation of how hover intent works, check out their website.

Conclusion

Keep in mind that this script calculates the width of your .sub container (adding up all UL’s per row) and automatically adjusts it. If you would like to specify your own custom width, you can delete that portion of the code and specify a static width in your CSS. This all depends on what you are trying to add in your mega drop down, and each scenario may be different. I hope you grasped the basic concepts of this tutorial so you can make your own custom mega drop down for future projects. If you have any questions, concerns, or suggestions, please let me know!

Mega Drop Down Menu - CSS & jQuery

This entry was posted in jQuery and tagged , , , , , , , , , , , . Bookmark the permalink.