michaelp0730
1/19/2015 - 6:17 PM

Image Cycle jQuery Plugin

// jQuery plugin to cycle through images 

(function($) {
    'use strict';

    var dataName = 'imgcycle',
        ImgCycle = function(element, options) {
            this.$element = $(element);
            this.options = $.extend({}, $.fn.imgcycle.defaults, options);
            this.init();
        };

    // Intialize Plugin
    $.fn.imgcycle = function(options) {
        return this.each(function(i, el) {
            var $this = $(this),
                data = $this.data(dataName);

            if (!data) {
                $this.data(dataName, (data = new ImgCycle(this, options)));
            }

            if (typeof options === 'string') {
                data[options]();
            }
        });
    };

    ImgCycle.prototype = {
        init: function() {
            var that = this;
            that.$images = this.$element.find('img');
            that.$prime = $(this.$images.get(0));
            that.imgs = [];
            that.$images.each(function(i, el) {
                that.imgs.push($(el).prop('src'));
            });

            that.index = null;
            that.showNext();

            if (this.options.autoplay === true) {
                this.start();
            }
        },

        showNext: function() {
            if(this.index === null) {
                this.index = 0;
                this.$prime.show();
            } else {
                this.index += 1;
                if (this.index >= this.$images.length) {
                    this.index = 0;
                }

                this.$prime.prop('src', this.imgs[this.index]);
            }
        },

        start: function() {
            var that = this;
            that.timeout = setInterval(function() {
                that.showNext();
            }, this.options.delay);
        },

        stop: function() {
            clearInterval(this.timeout);
        }
    };

    $.fn.imgcycle.defaults = {
        autoplay: true,
        delay: 1250
    };

}(jQuery));