adrianvlupu
9/16/2013 - 9:41 AM

My vision of the simplest slider ever

My vision of the simplest slider ever

(function ($) {
    $.fn.slider = function (method, options) {
        var methods = {
            init: function (options) {
                if ($(this).children().length > 0) {
                    var slide = $($(this).children().get(options.startIndex));
                    slide.addClass('selected');
                    options.onInit(options.startIndex);
                }
            },
            moveTo: function (command, options) {
                console.log('getData called', command, options, this);
                if (typeof command === 'number') {
                    $(this).children('.selected').removeClass('selected');
                    $($(this).children().get(command)).addClass('selected');
                } else if (typeof command === 'string') {
                    if (command == 'next') {
                        var next = $(this).children('.selected').index() + 1;
                        if ($($(this).children().get(next)).length == 0)
                            next = 0;
                        $(this).children('.selected').removeClass('selected');
                        $($(this).children().get(next)).addClass('selected');
                    } else if (command == 'prev') {
                        var next = $(this).children('.selected').index() - 1;
                        if ($($(this).children().get(next)).length == 0)
                            next = $(this).children().length - 1;
                        $(this).children('.selected').removeClass('selected');
                        $($(this).children().get(next)).addClass('selected');
                    }
                }
            }
            //add more functions here
        };
        return this.each(function (i, e) {
            if (methods[method]) {
                return methods[method].apply(this, [options, $(this).data('slider')]);
            } else if (typeof method === 'object' || !method) {
                //defaults
                options = $.extend(true, {
                    startIndex: 0,
                    onInit: function () {}
                }, method);
                $(this).data('slider', options);
                return methods.init.apply(this, [options]);
            } else {
                $.error('Method ' + method + ' does not exist');
            }
        });
    };
})(jQuery);