rikukissa
3/21/2013 - 1:08 PM

jQuery slider plugin

jQuery slider plugin

define (require) ->
  $ = require('jquery')
  
  $.fn.slider = (@opts = {}) ->
    slider = $(this)

     # Initialize slides
    $(this).find('.slide').each (i) ->
      $(this).attr('data-index', i)
      $(this).addClass('hidden-right').appendTo(slider) if i > 0

    @_minimized = false
    @_currentIndex = 0
    @_currentSlide = slider.find('.slide:first-child')
    
    if @opts.verticalResize? && @opts.verticalResize
      slider.stop().animate
        height: @_currentSlide.outerHeight(true)
      , 700


    @currentSlide = (i, opts = {}) =>
      return @_currentIndex if !i?

      if opts.slideFrom?
        if opts.slideFrom == 'right' then nextClass = 'hidden-right' else nextClass = 'hidden-left'
        if opts.slideFrom == 'right' then prevClass = 'hidden-left' else prevClass = 'hidden-right'
      else
        if i > @_currentIndex then nextClass = 'hidden-right' else nextClass = 'hidden-left'
        if i > @_currentIndex then prevClass = 'hidden-left' else prevClass = 'hidden-right'

      nextSlide = slider.find('[data-index="' + i + '"]')
        .addClass(nextClass).removeClass(prevClass).appendTo(slider)

      setTimeout =>
        slider.find('[data-index="' + @_currentIndex + '"]').addClass(prevClass)
        nextSlide.removeClass(nextClass)
        @_currentIndex = i
        @_currentSlide = nextSlide

        if @opts.verticalResize? && @opts.verticalResize
          slider.stop().animate
            height: nextSlide.outerHeight(true)
          , 700
      , 100
      this
    
    @nextSlide = (e) => 
      e.preventDefault?() if e?
      if @_currentIndex == slider.find('.slide').length - 1 # Nowhere to go to
        @currentSlide 0, slideFrom: 'right'
      else
        @currentSlide @_currentIndex + 1 
      this

    @prevSlide = (e) =>
      e.preventDefault?() if e?
      if @_currentIndex == 0 # Nowhere to go to
        @currentSlide slider.find('.slide').length - 1, slideFrom: 'left'
      else
        @currentSlide @_currentIndex - 1
      this

    @resize = => 
      return if !@_currentSlide.outerHeight(true)?
      slider.stop().animate height: @_currentSlide.outerHeight(true), 700 
      this

    @minimize = ->
      height = if @_minimized then @_currentSlide.outerHeight(true) else 0
      if @_minimized then @_minimized = false else @_minimized = true
      slider.stop().animate height: height, 700
      this

    $(window).on 'resize', @resize

    slider.find('.next-slide').click @nextSlide
    slider.find('.prev-slide').click @prevSlide

    this