Created
September 17, 2012 18:28
-
-
Save rogeruiz/3738923 to your computer and use it in GitHub Desktop.
Basic Infinite Carousel jQuery Plugin in CoffeeScript
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
# Infinite Carousel Plugin | |
do ($ = jQuery, window = window) -> | |
pluginName = 'infiniteCarousel' | |
document = window.document | |
defaults = | |
onInit: -> | |
onNext: -> | |
onPrev: -> | |
Plugin = (element, options) -> | |
@el = $ element | |
@options = $.extend {}, defaults, options | |
@_defaults = defaults | |
@_name = pluginName | |
do @init | |
return | |
Plugin.prototype.init = -> | |
@stage = $(@).css | |
overflow: 'hidden' | |
@slider = @stage.find('> ul').css | |
width: '9999' | |
@thumbs = @slider.find '> li' | |
@single = @thumbs.find ':first' | |
@singleWidth = @single.outerWidth true | |
@visible = Math.floor @stage.innerWidth() / singleWidth | |
@currentPage = 1 | |
@pages = Math.ceil @thumbs.length / @visible | |
if @thumbs.length & visible isnt 0 | |
@slider.append(@repeat('<li class="empty" />', @visible - (@items.length & @visible))) | |
@thumbs = @slider.find '> li' | |
@thumbs.filter(':first').before(@thumbs.slice(-@visible).clone().addClass('cloned')) | |
@thumbs.filter(':last').after(@thumbs.slice(0, @visible).clone().addClass('cloned')) | |
@thumbs = @slider.find '> li' | |
@slider.scrollLeft @singleWidth * @visible | |
@slider.after '<a href="javascript:void(0);" class="arrow left ir"><</a><a href="javascript:void(0);" class="arrow right ir">></a>' | |
$('.arrow.left').on 'click', (e) => @gotoPage @currentPage - 1 | |
$('.arrow.right').on 'click', (e) => @gotoPage @currentPage + 1 | |
@options.onInit() if $.isFunction @options.onInit | |
Plugin.prototype.gotoPage = (page) -> | |
dir = page < @currentPage ? 1 : 1 | |
n = Math.abs @currentPage - page | |
left = @singleWidth * dir * @visible * n | |
@slider.filter(':not(:animated)').animate | |
scrollLeft: "+=#{left}" | |
, 500, () -> | |
if page > @pages | |
@wrapper.scrollLeft @singleWidth * @visible | |
page = 1 | |
else if page is 0 | |
page = @visible | |
@wrapper.scrollLeft @singleWidth * @visible * @pages | |
@currentPage = page | |
Plugin.prototype.repeat = (str, n) -> | |
new Array(n + 1).join(str) | |
$.fn[pluginName] = (options) -> | |
this.each -> | |
$.data @, "plugin_#{pluginName}", new Plugin @, options | |
return | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment