jQuery: sliding and aligning panels

In this post I'm going to show you how to slide some panels into view and then align them with jQuery and a couple of CSS styles. First of all, the CSS float property doesn't work with jQuery animations. To accomplish this task, we're going to use the addClass() method instead. Let's start with a basic markup structure:

<div id="content">
 <div id="navigation"></div>

 <div class="panel"></div>
 <!--more panels-->
</div>

The first thing to do is to populate our navigation system with a series of links, each one containing a reference to a brand new ID created for each panel:

var panelID = 0;

    $('#content div.panel').each(function() {
    
    
        panelID += 1;
        
        $(this).attr('id', 'panel-' + panelID);
        
        $('<a/>').attr('href', '#panel-' + panelID).text(panelID).appendTo('#content #navigation');
        
        $(this).hide();
    
    
    
    });

All contents are now in place. We can add our styles:

body {margin: 0; padding: 2em 0;}

#content {
 padding: 0;
 width: 40em;
 margin: 0 auto;
 font: 76% Arial, sans-serif;
}

#content div.panel {
 padding: 0.5em;
 background: #000;
 color: #fff;
 border-radius: 14px;
 height: 12em;
 margin: 1em 0;
}

#content div.panel h2 {
 font: normal 1.8em "Times New Roman", Times, serif;
 color: #f50;
 margin: 0;
 padding: 5px 0;
 text-align: center;
}

#content div.panel p {
 line-height: 1.4;
 margin: 0;
}

#navigation {
 height: 2em;
 line-height: 2em;
 text-align: center;
 margin-bottom: 1em;
}

#navigation a {
 text-decoration: none;
 padding: 10px;
 background: #a40;
 color: #fff;
 font-weight: bold;
 font-size: 2em;
 margin-right: 5px;
 border-radius: 12px;
}

.slide {
 float: left;
 width: 30%;
 margin-right: 5px;
 height: 30em !important;
}

The CSS class will be used to align our panels:

$('#navigation a').each(function() {
    
    
        var $a = $(this);
        var id = $a.attr('href');
        
        $a.click(function(e) {
        
        
         $(id).show(1000, function() {
         
              $(this).addClass('slide').animate({
               opacity: '0.7'
              }, 1000);
              
         });
                    
            e.preventDefault();
        
        });
    
    
});

You can see a demo below:

Demo

Live demo

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.