Aliaspooryorik
ColdFusion ORM Book

jQuery mouseover expanding menu

A few years back, I wrote a post about Expanding Menus with jQuery. It's still quite popular and recently I was asked a question about how to have the menu expanded on page load if one of the elements has a class on it. As a result I thought this would be a good time to post an updated and improved version.


<ul id="nav">
<li>Heading 1
<ul>
<li>Sub page A</li>
<li>Sub page B</li>
<li>Sub page C</li>
</ul>
</li>
<li>Heading 2
<ul>
<li>Sub page D</li>
     <!--- the 'current' class is applied to the viewed page --->
<li class="current">Sub page E</li>
<li>Sub page F</li>
</ul>
</li>
<li>Heading 3
<ul>
<li>Sub page G</li>
<li>Sub page H</li>
<li>Sub page I</li>
</ul>
</li>
</ul>


<script>
jQuery(function($){
// by default hide all child nodes
$('#nav>
li>ul').hide();

// find li with a class of current
$currentnode = $('#nav li.current');

if ($currentnode.length){
// there is a node with the class of current so
// check to see if it has children
if ($currentnode.find('ul').length){
// the current node has children so show them
$currentnode.find('ul').show();
}
else if (!$currentnode.parent().is('#nav')){
// the current node is a child so show siblings
$currentnode.parent().show();
}
}

// code to handle expanding on mouseover
$('#nav>li').bind('mouseover', function(){
// check that the menu is not currently animated
if ($('#nav ul:animated').length==0) {
// create a reference to the active element (this)
// so we don't have to keep creating a jQuery object
$heading = $(this);
// create a reference to visible sibling elements
// so we don't have to keep creating a jQuery object
$expandedSiblings = $heading.siblings().find('ul:visible');
if ($expandedSiblings.length!=0) {
$expandedSiblings.slideUp(500, function(){
$heading.find('ul').slideDown(500);
});
}
else {
$heading.find('ul').slideDown(1000);
}
}
});
});
</script>

I've put a quick demo of it in action over on jsfiddle

 


No comments

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts