jQuery: slideup slidedown example

Yesterday I got a message on Facebook from my good friend Carlo who had a problem with jQuery and a series of headings followed by lists. Basically, Carlo wanted to know if it was possible to click on each heading and show the next list, while hiding the previous one. Also, only the first list had to be visible after the page has finished loading. I thought that this was actually a perfect example for illustrating the sliding features of jQuery. Let's start with our markup structure:

<div id="main">
  <h2>...</h2>
  <ul>...</ul>
  <h2>...</h2>
  <ul>...</ul>
  <!--same structure repeated other three times-->
</div>

A couple of CSS styles to present our structure:

#main {
 height: 100%;
 padding: 1em;
 background: #fff;
 border-radius: 12px;
 font-size: 1.2em;
}

#main h2 {
 margin: 0 0 1em 0;
 padding: 0.5em;
 background: #a40;
 color: #fff;
 font-size: 2em;
 border-radius: 12px;
 cursor: pointer;
}

#main ul {
 line-height: 1.4;
 padding: 0.3em 0 0.3em 2.5em;
 border-top: 1px dashed;
 border-bottom: 1px dashed;
 margin: 1em 0;
}

Now jQuery. Remember that the first list must be visible when the page has finished loading and the others hidden.

$(document).ready(function() {


  $('#main ul').not(':first').hide();

  $('#main h2').each(function() {
  
    var $h2 = $(this);
    var prevList = $h2.prev();
    var nextList = $h2.next();
    
    $h2.click(function() {
    
      if(prevList.is(':visible')) {
      
        prevList.slideUp();
      
      
      }
      
      if(nextList.is(':hidden')) {
      
        nextList.slideDown();
        
      }
    
    
    });
  
  
  });


});

First, we hide all the lists except the first one using the not() filter method. Then we loop over each heading and we check whether the next and previous list is visible or not. If a list is visible, we hide it using slideUp(). On the contrary, if a list is hidden, we show it using slideDown(). You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: slideup slidedown example”

Leave a Reply

Note: Only a member of this blog may post a comment.