Expand and Collapse is ideal for selective displaying information. it is frequently used in websites. It will let users to control, how the content is shown or hidden in the page. Today We are going to look how to create expand and collapse using jquery.
We will start with the markup
Without applying any style or jQuery code, the HTML file on execution displays the unordered list with its respective list items like this,
Now we will start our jquery code.
Download the Followings:
Styling with CSS
The css style "plusimageapply" will be applied to all the list items (in collapsed mode) that have a nested unordered list.
The css3 spec specifies that the list-item can modify using the pseudo-element "marker", unfotunatly no browser support for that. So we replace the bullet symbol with the image using list-style-image
Similarly, the style rule minusimageapply will be applied to all the list items in expanded mode, and it contains the list-style-image property set to url to display a minus icon on the left of the list items. The style rule selectedimage will be applied to all of the list items that do not have unordered list nested in them
Now looking at our jQuery code, all the list items of the class category (those that have unordered list items nested in them) the style rule plusimageapply will be applied, making a plus icon to appear on their left. To all the rest of the list items (that do not have nested list items in them), the style rule selectedimage will be applied.
We initially make all the nested elements of the list items (that have unordered list items in them) invisible. That is, we make all the list items that have unordered list items in them appear in collapsed mode.
To apply the expand functionality, we attach a click event to each of the list items (that has an unordered list item in it), one by one. In the event handler, we check whether the list item on which the click event has occurred has the style rule plusimageapply applied to it. If it does, we display the hidden contents of the list item.
We then remove the style properties of style rule plusimageapply and apply the style properties of the style rule minusimageapply to replace the plus icon with the minus icon for the expanded list items. If the list item that was clicked has a minus icon on its left—that is, if the style rule plusimageapply is not applied to it—we hide the nested contents. We also remove the style properties of style rule minusimageapply and apply the style properties of the style rule plusimageapply to replace the minus icon with the plus icon for the list items that is in collapsed mode (we need to collapse the list item that has the minusimageapply style rule applied on it and is clicked).