JQuery Collapsible Div

JQuery Collapsible Div

Here is simple code which demonstrate how to make div collapsible using JQuery. It can be achieved in many way. We will use JQuery toggle() function.

JQuery toggle example

In below example I’m finding html anchor element by it’s class name. This way I can attach click event to all anchor tag having class “myAnchorClass”. On click of hyper link I can get element next to it. and that’s nothing but my div element which I would be toggling.

<script type="text/javascript" language="javascript"> 
   
   $("document").ready(function(){
   
         $(".myAnchorClass").click(function(){

            $(this).next().toggle("slow");
 

            });
  
    });
   
</script>

You can use next() function to get next element of any clicked element.

Full HTML Example:

<html>
<head>
    <title>Jquery Change content of Div</title>
    <style>
   
     .myAnchorClass
    {
     display:block;
    }  
   
  </style>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript"> 
   
       $("document").ready(function(){
       
             $(".myAnchorClass").click(function(){
    
                $(this).next().toggle("slow");
     
    
                });
      
        });
   
    </script>

</head>
<body>
    <div>
        <a class="myAnchorClass" id="anchorID" href="#">Click to collapse and expand</a>
        <div id="div1">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
        <a class="myAnchorClass" id="a1" href="#">Click to collapse and expand</a>
        <div id="div2">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
        <a class="myAnchorClass" id="a2" href="#">Click to collapse and expand</a>
        <div id="div3">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
        <a class="myAnchorClass" id="a3" href="#">Click to collapse and expand</a>
        <div id="div4">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
        <a class="myAnchorClass" id="a4" href="#">Click to collapse and expand</a>
        <div id="div5">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
        <a class="myAnchorClass" id="a5" href="#">Click to collapse and expand</a>
        <div id="div6">
            This red div contains collpsible contents. </br> Ok, you can expand too.
        </div>
    </div>
</body>
</html>

Tags:

Jquery