jQuery Expand Collapse All

by Vincy. Last modified on July 6th, 2023.

The expand collapse functions are used for expanding or collapsing menu-structured or tree-structured lists of items. There are various plug-ins and UI effects in jQuery to provide expand collapse option.

This tutorial uses jQuery to show and hide functions to expand/collapse a list of menu items.

View Demo

HTML Menu to be Expanded/Collapsed

Let us take the list of menu items we used in a jQuery tutorial to show 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>

jQuery Expand Collapse Handler

We have to Expand All links in the above HTML code. On clicking this link, it will call the jQuery expand-collapse function. This function will collapse menu items if already in expanded mode and vice versa. 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");
	}
}

View DemoDownload

↑ Back to Top

Share this page