jQuery Ghost Carousel
by Amit Vishwakarma
HTML
<div id="ghostCarousel">
<div id="content">
<div id="a">
<p>Content A</p>
</div>
<div id="b">
<p>Content B</p>
</div>
<div id="c">
<p>Content C</p>
</div>
<div id="d">
<p>Content D</p>
</div>
<div id="e">
<p>Content E</p>
</div>
</div>
<div id="gcNav">
<a href="#" class="left"><<</a>
<a href="#" class="right">>></a>
</div>
</div>
CSS
html, body { padding: 0px; }
#ghostCarousel {
overflow: hidden;
}
#ghostCarousel #content > div {
width: 400px;
height: 300px;
float: left;
position: relative;
}
#ghostCarousel #content p {
padding: 20px;
}
#gcNav {
text-align: center;
}
#gcNav a {
padding: 5px;
}
#ghostCarousel #a { background-color: #8ECCED; }
#ghostCarousel #b { background-color: #70B9E0; }
#ghostCarousel #c { background-color: #55A7D4; }
#ghostCarousel #d { background-color: #3B94C4; }
#ghostCarousel #e { background-color: #247DAD; }
JavaScript
/* jQuery Ghost Carousel
* Copyright (c) 2011 William Moynihan
* http://ghosttype.com
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
* May 31, 2011 -- v1.0
*/
$(function() {
var content = '#ghostCarousel #content';
var section = content + ' > div';
function ghostCarousel() {
var v = $(window).width();
var w = $(section).width();
var c = (w * $(section).length - v) / 2;
$(content).width(w * $(section).length);
$(content).css('margin-left', -c);
$('#gcNav a.left').click(function(e) {
e.preventDefault();
if ($(content).is(':animated')) return false;
$(content).animate({ marginLeft: '-=' +w }, 1000, function() {
var first = $(section).eq(0);
$(section).eq(0).remove();
$(this).animate({ marginLeft: '+=' +w }, 0);
$(this).append(first);
});
});
$('#gcNav a.right').click(function(e) {
e.preventDefault();
if ($(content).is(':animated')) return false;
$(content).animate({ marginLeft: '+=' +w }, 1000, function() {
var end = $(section).length - 1;
var last = $(section).eq(end);
$(section).eq(end).remove();
$(this).animate({ marginLeft: '-=' +w }, 0);
$(this).prepend(last);
});
});
}
ghostCarousel();
$(window).resize(function() {
var v = $(window).width();
var w = $(section).width();
var c = (w * $(section).length - v) / 2;
$(content).css('margin-left', -c);
});
});
/* end "jQuery Ghost Carousel" */