facebook

How to create custom accordions using jQuery?

By Munmun Das

accordians in jquery

How to create custom accordions using jQuery?

 

The accordion is one of the useful elements. Accordion shows only one collapsible item at a time. But most importantly, an accordion shortens pages and reduce scrolling of the website. It can open and hide contents with a single click.

There are different types of accordions. In accordion, we use small heading or title that indicates what content is hidden. It also uses small icons or image to show that hidden content.

In short, an accordion is used for reducing some space in the working surface. Here, I have used a simple accordion with the help of CSS and JQuery.

You can follow these methods to open and close accordion.

 

 

 

HTML

<div class="accordion">
  <div class="group">
    <a href="#">Group-1</a>
    <p class="body-part">....</p>
    </a>
   </div>
</div>
<div class="accordion">
   <div class="group">
     <a href="#">Group-2</a>
     <p class="body-part">...</p>
     </a>
   </div>
</div>
<div class="accordion">
   <div class="group">
     <a href="#">Group-2</a>
     <p class="body-part">...</p>
     </a>
   </div>
</div>


CSS
<style>

.group .body-part{display:none;padding: 19px 25px;}
.accordion{border:1px solid #dfdbdb;padding: 25px 0;} 
.group{margin-top: -10px;margin-left: 21px;}
.group a::after{content:"+"; float:right;padding-right:-5px;margin-right: 31px;cursor: pointer;}
.active .group a::after{content:"-";}
.group a{display: block;font-size: 20px;}

</style>

JQuery

$(document).ready(function(){

   $(".accordion .group a").click(function(){
    if($(this).closest(".accordion").hasClass("active")) {
      $(this).closest(".accordion").removeClass("active");
      $(this).closest(".accordion").find(".body-part").slideUp();
    }else{
      $(".accordion").removeClass("active");
      $(".accordion").find(".body-part").slideUp();
      $(this).closest(".accordion").addClass("active");
      $(this).closest(".accordion").find(".body-part").slideDown();
    }
  })
})

Munmun Das Author
Web Designer , Openweb Solutions

Front-end Developer and Technology Enthusiast at Openweb Solutions

Posts created 11

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
shares