Created
January 20, 2015 20:58
-
-
Save gabrielgilini/d88bc8e0a04ae54bab3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(['underscore', 'jquery'], function (_, $) { | |
'use strict'; | |
var Slider = function (wrapperEl, options) { | |
var $wrapperEl = this.$wrapperEl = $(wrapperEl); | |
var $listEl = this.$listEl = $wrapperEl.find('ul'); | |
var $items = this.$items = $listEl.children(); | |
options = this.options = $.extend(true, { | |
animation: { | |
duration: 600, | |
ease: 'swing' | |
}, | |
nav: { | |
left: $wrapperEl.find('.slider-left'), | |
right: $wrapperEl.find('.slider-right'), | |
disabled: 'disabled' | |
}, | |
visible: 3 | |
}, options || {}); | |
this.calculateDimensions(); | |
$listEl.css('width', this.itemWidth * $items.length); | |
this.currentLeft = 0; | |
this.updateUI(); | |
if (!/relative|absolute/.test($listEl.css('position'))) { | |
$listEl.css('position', 'relative'); | |
} | |
$(options.nav.left).on('click', _.bind(this.slideLeft, this)); | |
$(options.nav.right).on('click', _.bind(this.slideRight, this)); | |
}; | |
Slider.prototype.calculateDimensions = function () { | |
var $firstItem = this.$items.eq(0); | |
this.itemWidth = $firstItem.outerWidth(true); | |
this.itemMargin = this.itemWidth - $firstItem.outerWidth(); | |
this.minLeft = -(this.itemWidth * (this.$items.length - this.options.visible)); | |
this.slideWidth = this.itemWidth * this.options.visible; | |
}; | |
Slider.prototype.updateUI = function () { | |
this.options.nav.left[this.canGoLeft() ? 'removeClass' : 'addClass'](this.options.nav.disabled); | |
this.options.nav.right[this.canGoRight() ? 'removeClass' : 'addClass'](this.options.nav.disabled); | |
}; | |
Slider.prototype.canGoLeft = function () { | |
return this.currentLeft < 0; | |
}; | |
Slider.prototype.canGoRight = function () { | |
return this.$items.length > this.options.visible && this.currentLeft > this.minLeft; | |
}; | |
Slider.prototype.animateTo = function (left) { | |
this.$listEl.animate({left: Math.min(0, Math.max(this.minLeft, left))}, this.options.animation.duration, this.options.animation.ease); | |
this.currentLeft = left; | |
this.updateUI(); | |
}; | |
Slider.prototype.slideLeft = function () { | |
if (this.canGoLeft()) { | |
this.animateTo(this.currentLeft + this.slideWidth); | |
} | |
}; | |
Slider.prototype.slideRight = function () { | |
if (this.canGoRight()) { | |
this.animateTo(this.currentLeft - this.slideWidth); | |
} | |
}; | |
return Slider; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment