PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Simple Accordian using Jquery

The following jquery script can be used to create an accordian effect. Add the class 'handler' to the clickable element and 'expandable' to the element that needs to be toggled.
<script type="text/javascript">
  $(document).ready(function () {
    $(".expandable").hide();
    $(".handler").click(function () {
      if ($(this).siblings(".expandable").css("display") == "none")
      {
        $(".expandable").hide();
        $(this).siblings(".expandable").slideDown();
      }
      else
      {
        $(".expandable").slideUp();
      }
    });
 });
</script>
Here is a working example which uses the above script
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple Jquery Accordian</title>
    <style type="text/css">
        .handler { width:300px; background-color:#d3d3d3; margin-bottom:10px; cursor: pointer;}
    </style>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".expandable").hide();
            $(".handler").click(function () {
                if ($(this).siblings(".expandable").css("display") == "none") {
                $(".expandable").hide();
                    $(this).siblings(".expandable").slideDown();
                }
            else
            {
                    $(".expandable").slideUp();
            }
            });
        });
    </script>
</head>
<body>
  <div>
   <h3 class="handler">One</h3>
   <ul class="expandable">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    </ul>
  </div>
  <div>
   <h3 class="handler">Two</h3>
   <ul class="expandable">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
   </ul>
  </div>
  <div>
   <h3 class="handler">Three</h3>
   <ul class="expandable">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
   </ul>
  </div>
  <div>
   <h3 class="handler">Four</h3>
   <ul class="expandable">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
   </ul>
  </div>
 </body>
</html>

and the above example when viewed in browser looks like the following, try clicking on any of the links below


One

Two

Three

Four

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2015