jQuery sliding content

Making content slide with jQuery requires some workaround if we want this happen by using a controller with links. We start with a basic markup like this:

<div id="extra">

  <div class="extra-box"></div>
  
  <!-- more extra boxes -->
  
  <div id="controller">
  
  <!-- pagination links here -->
  
  </div>

</div>

In this demo we're using real links for the sake of accessibility (generating links can be actually troublesome for browsers that don't support JavaScript). When an user clicks on a link, only the content related to that link will be showed. Here's the jQuery code:

$(document).ready(function() {

   $('div.extra-box').eq(0).nextAll().not('#controller').hide();
   
   var index = 0;
   var $id = 'box';
   var indexes = [];
   
   $('div.extra-box').each(function() {
   
       index++;
       
       $(this).attr('id', $id + index);
       
       indexes.push($(this).attr('id'));
   
   });
   
   
   for(var i=0; i<indexes.length; i++) {
   
   
       var $href = indexes[i];
       
       $('#controller a').eq(i).attr('name', $href); 
         
   
   }
   
   
   
   
   $('#controller a').each(function() {
   
        
        var $a = $(this);
        var $name = $a.attr('name');
        
        $('div.extra-box').each(function() {
           
               var $box = $(this);
               
               if($box.attr('id') == $name) {
               
                   if($box.is(':visible')) {
                   
                       $box.hide();
                   
                   }
               
               
               }           
           
       });

        
        $a.click(function() {
        
            $('div.extra-box').each(function() {
                        
            
               var $box = $(this);
               
               if($box.attr('id') == $name) {
               
                   if($box.is(':hidden')) {
                   
                   
                       $box.slideDown();
                       
                       $('#extra div.extra-box').not($box).slideUp();
                       
                                     
                   
                   }          
               
               }
            
            
            
            });
            
                   
        
        });
        
                 
   
   });
});

First, all boxes are hidden. Then we generate an ID for each box and a name attribute for the controller links using the same value of the IDs. Then, when an user clicks on a link, only the related box will be shown, while the others will be hidden. To achieve the sliding effect, we use the slideUp() and slideDown() methods. You can see the final result here.

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

Leave a Reply

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