JSFiddle - React, Tailwind, and code Playground
HTML
<!--
This sample demonstrates a technique for creating custom jQuery plugins.
It allows you to:
1) instantiate each plugin with or without options
2) call methods on each plugin, while maintaining the values are return
A new answer for this Stack Overflow question: http://bit.ly/jquery-custom-plugin
Authored by Kevin Jurkowski, 04/09/14
-->
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
CSS
div {
background: red;
height: 40px;
margin-top: 10px;
width: 40px;
}
JavaScript
(function($) {
var CustomPlugin = function($el, options) {
this._defaults = {
randomizer: Math.random()
};
this._options = $.extend(true, {}, this._defaults, options);
this.options = function(options) {
return (options) ?
$.extend(true, this._options, options) :
this._options;
};
this.move = function() {
$el.css('margin-left', this._options.randomizer * 100);
};
};
$.fn.customPlugin = function(methodOrOptions) {
var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;
if (method) {
var customPlugins = [];
function getCustomPlugin() {
var $el = $(this);
var customPlugin = $el.data('customPlugin');
customPlugins.push(customPlugin);
}
this.each(getCustomPlugin);
var args = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined;
var results = [];
function applyMethod(index) {
var customPlugin = customPlugins[index];
if (!customPlugin) {
console.warn('$.customPlugin not instantiated yet');
console.info(this);
results.push(undefined);
return;
}
if (typeof customPlugin[method] === 'function') {
var result = customPlugin[method].apply(customPlugin, args);
results.push(result);
} else {
console.warn('Method \'' + method + '\' not defined in $.customPlugin');
}
}
this.each(applyMethod);
...