jQuery carousel prototype (non-OOP implementation)
A prototype implementation of carousel that doesn't break when you click rapidly.
by dipish
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
/**
* Initialize carousel on specified container element
*/
function initCarousel(cont) {
var itemWidth = 150, // can be retrieved from DOM
itemSpacing = 10, // can be (somehow) retrieved from DOM
activeWidth = 200,
activeIndex,
contWidth,
items,
itemsLen;
cont = $(cont);
items = cont.find('li');
itemsLen = items.length;
contWidth = cont.innerWidth(); // container width
cont.on('click', 'li', function() {
selectItem(this);
});
// TODO allow this to be customizable!
// select first item
selectItem(0, false);
/**
* 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"
*/
function selectItem(itm, anim) {console.log('selectItem');
var 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
if(itm == 'next') {
actIdx = (activeIndex + 1) % itemsLen;
} else if (itm == 'previous' || itm == 'prev') {
actIdx = activeIndex - 1;
actIdx = (actIdx < 0) ? (itemsLen - 1) : actIdx;
} else {
actIdx = $(itm).index();
}
} else { // itm is a numeric index
actIdx = itm;
}
actEl = $(items[actIdx]);
// calculating target scrollLeft
actOffset =...