jQuery Code for Accordion

You are currently viewing jQuery Code for Accordion
  • Post author:
  • Post category:Guides
  • Reading time:3 mins read

In jQuery, Accordion is used for menus in the expandable and collapsible form. It gives an attractive look to the them. They look similar to tabs stacked together in a beautiful way. So for enhancing the look and feel of the menus and also for the ease of use, when you can make data which are less relevant inside a expandable menu, lets take a look at how can we create a simple accordion for us.

We will see jQuery code for Accordion, which is very simple and easy to understand.

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".accordion-example .header").click(function() {
if($(this).next("div").is(":visible")){
$(this).next("div").slideUp("slow");
}
else {
$(".accordion-example .content").slideUp("slow");
$(this).next("div").slideToggle("slow");
}
});
});
</script>

<style>
body {
background:teal;
margin:10px;
}
div {
background:#ffffff;
border: 2px solid;
text-align: left;
border-color:turquoise;
}
.header { font-size: 20px;}
.content { display: none; }
.accordion-example { margin: 150px; }
</style>

</head>
<body>
<div class="accordion-example">

<div class="header">Click to know about HTML</div>
<div class="content">HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It was finalized, and published, on 28 October 2014 by the World Wide Web Consortium (W3C). This is the fifth revision of the HTML standard since the inception of the World Wide Web.</div>

<div class="header">Click to know about CSS </div>
<div class="content">Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language.</div>

</div>
</body>
</html>

When you run this code in browser, you will see the following:

Accordion

Click on the “Click to know about HTML”. The description or the content will be displayed just below the heading. (Refer to the screenshot below)

Accordion_First_Option

Click on the “Click to know about CSS”. Similarly, the description or the content for CSS will be displayed just below the heading. (Refer to the screenshot below)

Accordion_Second_Option

I have made a very simple demo for implementing accordion. Take this as a base and you can modify the code and add features as per your requirement.