Create Custom Accordion in Jquery

Date Published: 29/04/2020Published By: JaiSchool

By using the action events of Jquery, we can make custom accordion in jQuery default. Basically, an accordion contains some information that is hidden. When the accordion title is clicked, the accordion content appears. It has a toggle effect. See accordion Image:-

jquery custom accordion
  • To create a custom accordion create a container <div id="con"></div> and design it in CSS.
  • Now, set two elements. First for the accordion title and second for accordion content Here, in the below example, for a title, I have used <header></header> and <p></p> for content.
  • First, you need to hide accordion content, We will display it later when toggled on the accordion title. So, make it display to none in the cascading style sheet.

Now its time for jQuery code. Insert jQuery CDN and define when header element is clicked then the display property will be in contrast of current CSS property and similarly for the second time and so on.

For that, use jQuery's slideToggle() method. If the element in which slideToggle() method is defined, has a CSS property display:none; then after clicking on the header element when it executes the display property will be display:block; and if has a display:block; then after it will be display:none; . This process goes on every time the click event is performed.

<!DOCTYPE html>
<html>
<head>
  <title>Jquery Custom Accordian</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <style>
    #con{
      width:70%;
      margin:40px auto;
      box-shadow:0px 0px 10px grey;
    }

    #con header{
      background-color:red;
      color:white;
      font-size:22px;
      font-weight:bold;
      text-align:center;
      padding:8px;
      box-sizing:border-box;
      cursor:pointer;
      font-family:sans-serif;

    }
    #con p{
      display:none;
      font-family:sans-serif;
      padding:10px;
      box-sizing:border-box;
    }

  </style>
</head>
<body>

  <div id="con">
    <header>Show Notifications !!!</header>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    	<img src="https://jaischool.com/wp-content/uploads/2019/12/Jaischool.com_-e1575352026662.png" alt="jaischool">
    </p>
  </div>

<script>
  $(document).ready(function(){
    $("#con header").click(function(){
      $("#con p").slideToggle(300);
    });
  });

</script>
</body>
</html>