jQuery Accordian Menu


 / Published in: JavaScript
 

You'll need to download the latest version of jQuery for this to work, as it is linked in the tag. CSS/XHTML included.

  1. <script language="javascript">
  2. $(document).ready(function() {
  3. $('.navchild').hide();
  4. $('.navgrandchild').hide();
  5. $('#navroot > li > a, .navchild > li > a').click(function() {
  6. var visibility = $(this).next('ul').css("display");
  7. if( visibility == "none" )
  8. {
  9. $(this).next('ul').show("normal");
  10. $(this).parent().siblings().children('ul:visible').hide("normal");
  11. $('.navgrandchild').hide();
  12. $('#message').text($(this).text() + " Opened");
  13. }
  14. else { $(this).next('ul').hide("normal"); $('#message').text($(this).text() + " Closed");}
  15. });
  16. });
  17. </script>
  18.  
  19. <div id="navigation">
  20. <ul id="navroot">
  21. <li>
  22. <a href="#">Root 1</a>
  23. <ul class="navchild">
  24. <li><a href="#">Sub 1</a></li>
  25. <li><a href="#">Sub 2</a></li>
  26. </ul>
  27. </li>
  28.  
  29. <li>
  30. <a href="#">Root 2</a>
  31. <ul class="navchild">
  32. <li><a href="#" class="child">Child 1</a></li>
  33. <li><a href="#" class="child">Child 2</a></li>
  34. </ul>
  35. </li>
  36.  
  37. <li>
  38. <a href="#">Root 3</a>
  39. <ul class="navchild">
  40. <li>
  41. <a href="#">Child 1</a>
  42. <ul class="navgrandchild">
  43. <li><a href="#">Grandchild 1</a></li>
  44. <li><a href="#">Grandchild 2</a></li>
  45. </ul>
  46. </li>
  47. <li>
  48. <a href="#" >Child </a>
  49. <ul class="navgrandchild">
  50. <li><a href="#">Grandchild 1</a></li>
  51. <li><a href="#">Grandchild 2</a></li>
  52. </ul>
  53. </li>
  54. </ul>
  55. </li>
  56.  
  57. <li>
  58. <a href="#">Root 4</a>
  59. <ul class="navchild">
  60. <li><a href="#">Child 1</a></li>
  61. <li><a href="#">Child 2</a></li>
  62. </ul>
  63. </li>
  64. </ul>
  65. </div>
  66.  
  67. <div id="message">
  68. </div>
  69.  
  70. body {
  71. margin: 0;
  72. padding: 0;
  73. }
  74.  
  75. #navigation {
  76. float: left;
  77. width: 200px;
  78. background: #333;
  79. padding: 20px;
  80. }
  81.  
  82. #navigation li, ul {
  83. list-style: none;
  84. padding: 0;
  85. margin: 0;
  86. }
  87.  
  88. #navigation li a {
  89. display: block;
  90. color: #fff;
  91. width: 100px;
  92. padding: 5px;
  93. text-decoration: none;
  94. }
  95.  
  96. #navroot > li > a {
  97. background: #000;
  98. }
  99.  
  100. .navchild li a {
  101. background: #666;
  102. }
  103.  
  104. .navgrandchild li a {
  105. background: #999;
  106. }
  107.  
  108. #message {
  109. float: left;
  110. background: #666;
  111. padding: 20px;
  112. font-size: 2.0em;
  113. color: #fff;
  114. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Snowalker on November 30, 2011

this is great! thanks for sharing the whole code :)

You need to login to post a comment.