Created
September 20, 2016 19:58
-
-
Save angellromero/8375068bf99b77e5929c9a2a228ec694 to your computer and use it in GitHub Desktop.
A Random Plugin for Owl Carousel
This file contains hidden or 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
/** | |
* Random Plugin | |
*/ | |
;(function($, window, document, undefined) { | |
'use strict'; | |
/** | |
* Creates the random plugin. | |
* @class Random Plugin | |
* @param {Owl} carousel - The Owl Carousel | |
*/ | |
var Random = function(carousel) { | |
/** | |
* Reference to the core. | |
* @protected | |
* @type {Owl} | |
*/ | |
this._core = carousel; | |
/** | |
* The carousel element. | |
* @type {jQuery} | |
*/ | |
this.$element = this._core.$element; | |
/** | |
* All event handlers. | |
* @protected | |
* @type {Object} | |
*/ | |
this._handlers = { | |
'initialize.owl.carousel': $.proxy(function(e) { | |
if (e.namespace && this._core.settings.random) { | |
this.randomize(); | |
} | |
}, this) | |
}; | |
// Set default options | |
this._core.options = $.extend({}, Random.Defaults, this._core.options); | |
// Register the event handlers | |
this.$element.on(this._handlers); | |
}; | |
/** | |
* Default options. | |
* @public | |
*/ | |
Random.Defaults = { | |
random: false | |
}; | |
Random.prototype.randomize = function() { | |
var _self = this, | |
randomChildren = this.shuffle(_self.$element.children()); | |
randomChildren.each(function() { | |
$(this).appendTo(_self.$element); | |
}); | |
}; | |
Random.prototype.shuffle = function(array) { | |
var currentIndex = array.length, | |
temporaryValue, | |
randomIndex ; | |
// While there remain elements to shuffle... | |
while (currentIndex !== 0) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
// And swap it with the current element. | |
temporaryValue = array[currentIndex]; | |
array[currentIndex] = array[randomIndex]; | |
array[randomIndex] = temporaryValue; | |
} | |
return array; | |
}; | |
/** | |
* Destroys the plugin. | |
* @public | |
*/ | |
Random.prototype.destroy = function() { | |
for (var handler in this._handlers) { | |
this._core.$element.off(handler, this._handlers[handler]); | |
} | |
for (var property in Object.getOwnPropertyNames(this)) { | |
typeof this[property] != 'function' && (this[property] = null); | |
} | |
}; | |
$.fn.owlCarousel.Constructor.Plugins.Random = Random; | |
})(window.Zepto || window.jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment