Making slideToggle() elements collapsed by default in jQuery

You will have to assign a style: display:none to these layers, so that they are not displayed before javascript rendering. Then you can call slideToggle() without problems. Example:

<style type="text/css">
    .text{display:none}
</style>

<script type="text/javascript">
    $(document).ready(function() {    
        $('span.more').click(function() {
            $('p:eq(0)').slideToggle();
            $(this).hide();
        });
    });
</script>

<body>              
      <p class="text">
          I am using jquery <br/>
          I am using jquery <br/>
          I am using jquery <br/>
          I am using jquery <br/>
          I am using jquery <br/>
          I am using jquery <br/>           
      </p>
      <span class="more">show</span>

you probably can do something like this:

$(document).ready(function(){
  $('div').hide();
});

You can start your elements with style="display: none;" and slideToggle() will take it from there.


Applying a CSS style behind the scenes will, as stated before, cause complications for users with scripts disabled. A way around this is to declare your element hidden as Anne said, or by defining your CSS in your script as a function to be altered, not as styling for the page (to keep structure, style and function separate) and then using the toggleClass function of the script or the custom effect hide functions defined by jQuery.

Tags:

Jquery