Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For a menu with multiple items in list, I used slideToggle() to show / hide the items. However, in the initial state. all of items are shown. I want to change the initial state to be off for the listed items. How can it be done? Thanks in advance. The related code in my project is below:
JavaScript
    $(function () {
        $("#menu > li").click(function () {
            $(this).children("ol").slideToggle();
        });
    });
    ....
<ul id="menu">
  <li>Menu Item 1
    <ol>
      <li><a href="#">Sub Item 1.1</a></li>
      <li><a href="#">Sub Item 1.2</a></li>
    </ol>
  </li>
</ul>
Posted

Add one line to hide the sub items as soon as the load completes;
PHP
$(function(){
   var $selector = $("#menu > li")
   $selector.children("ol").hide();
   $selector.click(function () {
   $($selector).children("ol").slideToggle();
   });
});
 
Share this answer
 
v3
Comments
[no name] 13-Mar-14 11:10am    
Should this piece of code embedded in the existing function? I tested it w/o the existing function, and it does not work. Thanks.
Peter Leow 13-Mar-14 11:39am    
replace the existing jquery function, see enhanced solution.
Just add a "display:none" to the "ol". This will hide the sub item's until you click on "Menu Item 1", then they will slide down

HTML
<ul id="menu">
   <li>Menu Item 1
     <ol style="display:none">
       <li><a href="#">Sub Item 1.1</a></li>
       <li><a href="#">Sub Item 1.2</a></li>
     </ol>
   </li>
 </ul>
 
Share this answer
 
Comments
[no name] 13-Mar-14 11:08am    
SR: Thanks for your code. It works somehow, which means the items initially in 'hide' status. However, once the items are in 'show' status, they can be in 'hide' again. Could you advise me for additional code to toggle the 'show' and 'hide'? Thanks.
Shelby Robertson 13-Mar-14 11:14am    
The slide toggle would take care of that. Is there another situation where you would want to hide all of the sub items?
[no name] 13-Mar-14 11:17am    
SR: As mentioned, after toggle to 'show', re-toggle does not 'hide', just re-'show'.
Shelby Robertson 13-Mar-14 11:19am    
I'm not seeing that happen. Are you double clicking the menu item perhaps?

http://jsfiddle.net/wV56B/
[no name] 13-Mar-14 11:59am    
Rested it using existing code, which works. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900