How to create a simple accordion with JQuery

Accordions are very useful whenever we want to show content in an organized way. When we have set of lists with little description about each element, accordions can be a good option to show the data. This gives good user experience.

In this post, we will see how to create a simple accordion using HTML, CSS and JQuery.

Following are the steps to create JQuery accordion:

  • Create a HTML page with accordion structure.
  • Include CSS to add little style.
  • Add required JQuery script for accordion.

Create a HTML page with accordion structure

First step is to create a HTML template and add required basic HTML elements for our accordion. Create a simple HTML page and add the following content to the page.

 <h2 align="center">Simple Accordion</h2>
 < div class="container">
  < div class="tabs">
    <h4><span>Tab 1</span><span class="icons">-</span></h4> 
    < div class="tab-content" style="display: block;"> 
      <p>Tab 1 content<p> 
  < div class="tabs">
   <h4><span>Tab 2</span><span class="icons">+</span></h4>
   < div class="tab-content" style="display: none;"> 
    <p>Tab 2 content</p>
  < div class="tabs">
   <h4><span>Tab 3</span><span class="icons">+</span></h4>
   < div class="tab-content" style="display: none;">
    <p>Tab 3 content</p> 

Here, we have 3 tabs in our accordion structure. Each accordion contains a tab header and a +/- symbol on right corner to indicate whether accordion is open or not.

Include CSS to add little style

add the following CSS to make our accordion a nicely look.

< style>
.tabs h4 { 
font-family: Arial; 
color: #fff; 
padding: 6px; 
cursor: pointer; 
background: #2fa8f7; 
margin-bottom: 0px; 
border: solid 1px; 
border-color: grey; 
display: block; 
height: 50px; 
background : #D3D3D3; 
margin: 1%; 
float: right;  
font-size: 20px; 

Above CSS properties will give our accordion header a sky blue background with required padding and fonts.

Add required JQuery script for accordion

Final step is to add accordion functionality to our above created accordion structure.

Import JQuery library by including it on <header> of the page as shown below.

< script src=""></script>

Finally, add the following JQuery script to the HTML page.

< script>
$('body').on('click','.tabs h4', function() { 
  var $content = $(this).next('.tab-content'); 
  var $allContent = $(this).parent().parent().find('.tab-content'); 
  if ($':visible')) { 
    if ($':visible')) { 
  else { 

Here, our first accordion tab is in open state by default on page load. Once user clicks on any accordion tab, other tabs gets closed and on the accordion tab, which is clicked by user gets opened. If user clicks again on opened accordion tab, tab gets closed.

Following is the final look of our simple JQuery accordion.


Also read,