jQuery carousel prototype (OOP implementation)
A prototype implementation of carousel that doesn't break when you click rapidly.
by martions
HTML
<div class="carousel" id="myCarousel">
<ul class="carousel-items-container">
</ul>
</div>
<button id="lft"><</button>
<button id="rgt">></button>
CSS
body {
padding: 20px;
}
button {
padding: 5px 10px;
}
.carousel {
overflow: hidden;
width: 700px;
height: 200px;
border: solid 1px black;
white-space: nowrap;
/* make it unselectable */
-webkit-user-select: none;
-moz-user-select:-moz-none;
-khtml-user-select:none;
}
.carousel.debug {
overflow: auto;
}
.carousel-items-container {
width: 999999px;
}
.carousel-items-container li {
list-style-type: none;
float: left;
background: #aad6f7;
margin-right: 10px;
margin-top: 20px;
width: 150px;
height: 150px;
line-height: 150px;
font-size: 72px;
text-align: center;
font-family: sans-serif;
color: #751C00;
overflow: hidden;
}
.carousel-items-container .active {
background: #FF7D54;
color: #2E4468;
}
JavaScript
/**
* @constructor
* @param {String|HTMLElemnt|jQuery} cont Carousel container element
*/
function SuperCarousel(cont) {
// initialization code...
var me = this; // create closure
// ensure we have jQuery object
cont = $(cont)
this.cont = cont;
this.items = cont.find('li');
this.itemsLen = this.items.length;
this.contWidth = cont.innerWidth(); // container width
cont.on('click', 'li', function() {
me.selectItem(this);
});
// TODO allow this to be customizable!
// select first item
this.selectItem(0, false);
}
// defining SuperCarousel prototype
$.extend(SuperCarousel.prototype, {
// CONFIG
itemWidth: 150,
itemSpacing: 10,
activeWidth: 200,
// RUNTIME
activeIndex: null,
contWidth: null,
items: null,
itemsLen: null,
// METHODS
/**
* Selects an item inside carousel
* @param {String|Number|HTMLElemnt|jQuery element} itm Item to select
* @param {Boolean} anim Animation flag, the default value is "true"
*/
selectItem: function(itm, anim) {
var cont = this.cont,
activeIndex = this.activeIndex,
items = this.items,
itemsLen = this.itemsLen,
itemWidth = this.itemWidth,
itemSpacing = this.itemSpacing,
activeWidth = this.activeWidth,
actIdx, // index of target element
actEl, // target element
actOffset, // offset of target element from the first item
centeredOffset, // offset of target element from container's left margin needed to center it
targScrollLeft, // calculated target scrollLeft
easing,
duration;
// normalizing input parameters
anim = (typeof anim === 'undefined') ? true : anim; // animation on by default
if(isNaN(itm)) { // not a number - either a magic string or element object
...