
The expand collapse functions are used for expanding or collapsing menu structured or tree structured list of items. There are various plug-ins, UI effects in jQuery to provide expand collapse option. In this tutorial, we are using jQuery show and hide functions to expand/collapse list of menu items.
Let us take the list of menu items we have used in a jQuery tutorial for showing the drop-down menu. The code is,
<div onclick="expandCollapse()" id="expand-collapse" align="right">Expand All</div> <div id="popular" class="mainmenu"> <a href="#">Popular Toys</a> <div class="submenu"> <ul> <li><a href="#">Video Games</a> <li><a href="#">Barbies</a> <li><a href="#">Teddy Bear</a> <li><a href="#">Golf Set</a> </li></ul> </div> </div> <div id="recent" class="mainmenu"> <a href="#">Recent Toys</a> <div class="submenu"> <ul> <li><a href="#">Yoyo</a> <li><a href="#">Doctor Kit</a> <li><a href="#">Puzzles</a> <li><a href="#">Uno Cards</a> </li></ul> </div> </div> <div id="category" class="mainmenu"> <a href="#">Toys Category</a> <div class="submenu"> <ul> <li><a href="#">Battery Toys</a> <li><a href="#">Remote Toys</a> <li><a href="#">Magnet Toys</a> <li><a href="#">Soft Toys</a> </li></ul> </div> </div>
We have to Expand All link in the above HTML code. On clicking this link it will call the jQuery expand-collapse function. This function will collapse menu items if it is already in expanded mode and vise verse. The script is,
function expandCollapse() { if($(".submenu").css('display') == 'none') { $("#expand-collapse").html("Collapse All"); $(".submenu").show("slow"); } else { $("#expand-collapse").html("Expand All"); $(".submenu").hide("slow"); } }