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 a set of lists with a little description of each element, accordions can be a good option to show the data. This gives a good user experience. Using the JQuery library, we can implement accordion with ease.

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

Table of Contents

Create an HTML page for implementing JQuery accordion

The first step is to create an HTML template and add the 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 the right corner to indicate whether the accordion is open or not.

Include CSS to add little style

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

.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

The final step is to add accordion functionality to our 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.

$('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 an open state by default on page load. Once the user clicks on any accordion tab, other tabs get closed and the accordion tab, which is clicked by the user gets opened. If the user clicks again on opened accordion tab, the tab gets closed.

Following is the final look of our simple JQuery accordion.



In this article, we learned how to create a simple accordion using HTML, CSS, and JQuery.