jQuery Carousel

by Amit Vishwakarma

HTML

<div class="panels">
    <span class="left">&#060;&#060;</span>
    <span class="right">&#062;&#062;</span>
    <div class="inner">
        <div id="p1">
            <div class="content">Panel 1</div>
        </div>
        <div id="p2">
            <div class="content">Panel 2</div>
        </div>
        <div id="p3">
            <div class="content">Panel 3</div>
        </div>
        <div id="p4">
            <div class="content">Panel 4</div>
        </div>
        <div id="p5">
            <div class="content">Panel 5</div>
        </div>
    </div>
</div>

CSS

body, html { margin: 0px; padding: 0px; }

.panels {
    overflow: hidden;
    margin-top: 30px;
}
.inner > div {
    width: 970px;
    height: 300px;
    background-color: #ccc;
    float: left;
    position: relative;
}
.content {
    padding: 20px;
}
.left, .right {
    z-index: 10;
    display: block;
    position: absolute;
    height: 20px;
    background-color: #555;
    text-align: center;
    margin-top: 140px;
    padding: 0px 5px;
    color: #ccc;
}
.left:hover, .right:hover {
    background-color: #777;
    cursor: pointer;
}
.right {
    right: 0px;
}

JavaScript

$(function () {
   
    var w = $('.inner > div').width(); // width of one panel
    $('.inner').width(w * $('.inner > div').length); // set to width of all panels
    // left side click
    $('.left').click(function() {
        if ($('.inner').is(':animated')) return false;
        var pos = parseInt($('.inner').css('margin-left'));
        
        // if at end, goto beginning. Else move one panel
        if ( pos == -(w * $('.inner > div').length - w)) {
            $('.inner').animate({ 'margin-left' : '0px' }, 2000); 
        } else {
            $('.inner').animate({ 'margin-left' : '-=' + w }, 1000);
        }
    });
    // right side click
    $('.right').click(function() {
        if ($('.inner').is(':animated')) return false;
        var pos = parseInt($('.inner').css('margin-left'));
        
        // if at end, goto beginning. Else move one panel
        if ( pos == 0) {
            $('.inner').animate({ 'margin-left' : -(w * $('.inner > div').length - w) }, 2000); 
        } else {
            $('.inner').animate({ 'margin-left' : '+=' + w }, 1000);
        }
    });
    
});