Simple Circular Carousel
by Justin
HTML
<div class="container">
<div class="carousel">
<ul>
<li><img src="http://lorempixel.com/500/100/nature/1"/></li>
<li><img src="http://lorempixel.com/500/100/nature/2"/></li>
<li><img src="http://lorempixel.com/500/100/nature/3"/></li>
</ul>
<a class="nav prev" href="#"><</a>
<a class="nav next" href="#">></a>
</div>
</div>
CSS
.container {
width: 100%;
max-width: 500px;
height: 100px;
margin: 0 auto;
background-color: #666;
}
.carousel {
position: relative;
height: 100px;
width: 100%;
overflow: hidden;
}
.carousel ul {
list-style: none;
padding: 0;
margin: 0;
}
.carousel ul li {
float: left;
height: 100px;
}
a.nav {
display: block;
position: absolute;
top: 0;
width: 20px;
height: 100px;
text-decoration: none;
line-height: 100px;
font-size: 20px;
font-weight: bold;
color: transparent;
background-color: transparent;
text-align: center;
}
a.nav.prev {
left: 0;
}
a.nav.next {
right: 0;
}
a.nav.prev:hover,
a.nav.next:hover {
color: #fff;
background-color: rgba(0,0,0,0.3);
}
JavaScript
var $ul = $('.carousel ul');
var $lis_base = $ul.children();
$first = $lis_base.first();
$last = $lis_base.last();
$ul.append($first.clone())
.prepend($last.clone());
$first.addClass('active');
var $lis = $ul.children();
var n = $lis.length;
$ul.css('width', (100 * n) + '%');
$lis.css('width', (100 / n) + '%');
// initial offset
var activeOffset = function() {
return '-' + 100 * $('.carousel ul li.active').index() + '%';
};
$ul.css('margin-left', activeOffset());
$('a.nav.prev').on('click', function(e) {
e.preventDefault();
var $li = $ul.find('li.active');
if ($li.prev().length) {
$li = $li.removeClass('active').prev().addClass('active');
$ul.animate({'margin-left':'+=100%'}, 1000, function() {
if ($li.prev().length == 0) {
$li.removeClass('active');
$last.addClass('active');
$ul.css('margin-left', activeOffset());
}
});
}
});
$('a.nav.next').on('click', function(e) {
e.preventDefault();
var $li = $ul.find('li.active');
if ($li.next().length) {
$li = $li.removeClass('active').next().addClass('active');
$ul.animate({'margin-left':'-=100%'}, 1000, function() {
if ($li.next().length == 0) {
$li.removeClass('active');
$first.addClass('active');
$ul.css('margin-left', activeOffset());
}
});
}
});