Simple jQuery Accordion
Toggle elements on a web page
View the working demo here.
Accordions could be useful for representing frequently asked questions or child menu items. There could be many other scenarios accordions could be used. I would leave it to your imagination to decide that. Basically, they help to organize unimportant text on the webpage, so it is only visible when the user clicks to view it.
We are going to create a simple accordion with using jQuery, HTML and CSS. So lets get started.
HTML
The layout is pretty basic.
We have a wrapper div of class accordion. The wrapper has divs with class accordion-item. These are used as the header of accordion elements. The user would see these and they are made clickable to view the hidden data.
Each div of class accordion-item has a div of class type. This div has the image + or - based on whether the accordion item is open or not.
Each div of class accordion-item is followed by div of class data. These are the div which have the detailed information which is available when the accordion-item is clicked.
CSS
Following is the CSS used to style the elements. It is doing some basic styling to give accordion-item a different background color depending on whether the item is open or closed.
jQuery
It’s amazing how simple jQuery can make our lives. This is a simple code snippet that is required to create simple accordion.
Line 2: creates a variable representing all data divs within the div of class accordion
Line 3: creates a variable representing all the accordion-items with the div of class accordion
Line 4: function run when an accordion-item is clicked
Line 5: Hides all open data divs
Line 6: Removes class open from all divs of class accordion-item
Line 7: Adds class open to the div of class accordion-item which is clicked. This would change the background color and change the image to the right from “plus” sign to a “minus” sign
Line 8: Shows the data div next to the div of class accordion-item clicked.