I am creating one simple custom jQuery plugin using jquery.boilerplate.js. Now I want to create one function that will call like,
var div1 = $("#div1").changeBackgroundColor({
color: $('#colorCode').val().trim()
});
div1.getColor();
How to defined that getColor() method in jquery plugin.
Custom Plugin:
;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor", defaults = {
color : "black"
};
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init : function() {
console.log("Hello");
}
});
$.fn[pluginName] = function(options) {
this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this,
options));
}
console.log(options);
if(options===undefined){
$(this).css("background-color", defaults.color);
} else{
$(this).css("background-color", options.color);
}
});
return this;
};
})(jQuery, window, document);
Thank You....:)
You kinda missed the whole point of plugins and OOP.
$.fn[pluginName] - should play infrastructure role and delegate actual work to the Plugin instance.
Plugin instance should perform actual work with element.
If you want to call methods on Plugin instances you can make $.fn[pluginName] to handle special cases when options is a string. $(selector).changeBackgroundColor('methodToBeCalled' /*rest arguments*/)
Demo.
;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor",
defaults = {
color : "black"
},
//methods to be called via $().changeBackgroundColor(name)
publicMethods = {
getColor: function() {
return this.settings.color;
},
setColor: function(color) {
this.settings.color = color;
this.element.css('background-color', color);
}
},
privateMethods = { //internal methods
init : function() {
console.log('init');
this.setColor(this.getColor());
}
};
function Plugin(element, options) {
this.element = $(element);
this.settings = $.extend({}, defaults, options);
this.init();
}
//copy private and public methods
$.extend(Plugin.prototype, privateMethods, publicMethods);
$.fn[pluginName] = function(options) {
var out = [],
args = [].slice.call(arguments, 1);
this.each(function() {
var plugin = $.data(this, pluginName),
method;
if (!plugin) { //create new plugin
plugin = new Plugin(this, options)
return $.data(this, pluginName, plugin);
}
//handle method calls
if(typeof options === 'string' && publicMethods[options]) {
out.push(plugin[options].apply(plugin, args));
}
});
return out.length ? (out.length === 1 ? out[0] : out) : this;
};
})(jQuery, window, document);
Usage
$('#a').changeBackgroundColor();
$('#b').changeBackgroundColor({color: 'navy'});
$('#c').changeBackgroundColor({color: 'green'});
console.log($('#b').changeBackgroundColor('getColor'));
console.log($('#b, #c').changeBackgroundColor('getColor'));
$('#a').changeBackgroundColor('setColor', 'red');
console.log($('#a').changeBackgroundColor('getColor'));
Define your method like this
$.fn.getColor = function() {
alert('getColor called');
}
Basic Custom Plugin
Create your Plugin like this:
$.fn.highlight = function(){
this.css("background","yellow").css("color","black");
return this;
}
$(".highlight").highlight().fadeIn();
In the above example i had created a simple jQuery plugin which will highlight a element.I think you should check this http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/
Related
I have started jQuery plugin where I want to retrieve the .duration and .currentTime on a HTML5 video, from within a bound .on('click', ) event.
I am struggling to capture this information within my plugin.registerClick function, here is my code:
(function ($) {
$.myPlugin = function (element, options) {
var defaults = {
videoOnPage: 0,
dataSource: 'data/jsonIntervals.txt',
registerClick: function () { }
}
var plugin = this;
plugin.settings = {}
var $element = $(element);
element = element;
plugin.init = function () {
plugin.settings = $.extend({}, defaults, options);
$element.on('click', plugin.registerClick);
getJsonIntervals();
}
plugin.registerClick = function () {
var duration = $('video').get(plugin.settings.videoOnPage).duration;
console.log('duration: ' + duration);
}
var startTimes = [];
var dataSet = false;
var getJsonIntervals = function () {
if (dataSet == false) {
//calls a $.getJSON method.
//populates startTimes
//updates dataSet = true;
};
}
plugin.init();
}
$.fn.myPlugin = function (options) {
return this.each(function () {
if (undefined == $(this).data('myPlugin')) {
var plugin = new $.myPlugin(this, options);
$(this).data('myPlugin', plugin);
}
})
};
})(jQuery);
$(function () {
$('#button1').myPlugin();
});
Here my sample jsFiddle Click Here
Seems to work for me:
plugin.registerClick = function () {
var video = $('video').get(0);
console.log('duration: ' + video.duration);
console.log('currenttime: ' + video.currentTime);
}
http://jsfiddle.net/p4w040uz/2/
You need to play the video first then click the button. The browser has to retrieve the meta data first before it can return it.
Additional reference material you can read up:
http://www.w3schools.com/tags/av_event_loadedmetadata.asp
http://www.w3.org/2010/05/video/mediaevents.html
I`m trying to understand jQuery plugins and how to reference objects within other functions. So, I have this:
(function($) {
var methods = {
init: function (options) {
return this.each(function () {
var defaults = {
var1 : 'variable1',
var2 : 'variable2'
};
this.settings = $.extend(defaults,options);
});
},
add: function () {
// Access settings object here...how??
alert(this.settings.var1); ????
}
};
jQuery.fn.pluginName = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this,arguments);
} else {
console.error('Method '+method+' does not exist in plugin. Plugin aborted.');
}
};
}(jQuery));
So, my question is, once I have initialised the plugin, how can I reference the settings object inside the 'add' function when the 'add' function is called?
Thank you very much for any assistance.
The problem is the context value of this.
(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var defaults = {
var1: 'variable1',
var2: 'variable2'
};
//here this is the dom object not the wrapping jQuery object
this.settings = $.extend(defaults, options);
});
},
add: function() {
//here this is the jQuery object
return this.each(function() {
//here this is again the dom object
console.log(this.settings.var1);
})
}
};
jQuery.fn.pluginName = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
console.error('Method ' + method + ' does not exist in plugin. Plugin aborted.');
}
};
}(jQuery));
$('div').pluginName({
var1: 'x'
});
$('div').pluginName('add')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I would recommend using the data api instead of attaching the settings object directly to the dom element reference
One basic boilerplate that I use for plugins is
(function($) {
function PluginName(el, settings) {
//your initialization code goes here
this.$el = $(el);
this.settings = $.extend({}, jQuery.fn.pluginName.defaults, settings);
}
PluginName.prototype.add = function() {
console.log('add', this, arguments);
}
PluginName.prototype.result = function() {
console.log('result', this, arguments);
return 'result'
}
PluginName.prototype._add = function() {
console.log('not called');
}
jQuery.fn.pluginName = function(method) {
var result, args = arguments;
this.each(function() {
var $this = $(this),
data = $this.data('pluginName');
if (data) {
if (/^[^_]/.test(method) && typeof data[method] == 'function') {
result = data[method].apply(data, Array.prototype.slice.call(args, 1));
if (result !== undefined) {
return false;
}
} else {
throw new Error('Unable to find the method ' + method);
}
} else if (typeof method == 'object') {
data = new PluginName(this, method);
$this.data('pluginName', data);
} else {
throw new Error('Illegal arguments passed');
}
})
return result === undefined ? this : result;
};
jQuery.fn.pluginName.defaults = {
var1: 'variable1',
var2: 'variable2'
};
}(jQuery));
$('div').pluginName({
var1: 'x'
});
try {
$('div').pluginName('add', 3, 5)
} catch (e) {
console.log(e);
}
try {
$('div').pluginName('add2', 3, 5)
} catch (e) {
console.log(e);
}
try {
$('div').pluginName('_add', 3, 5)
} catch (e) {
console.log(e);
}
try {
var x = $('div').pluginName('result', 3, 5);
console.log(x)
} catch (e) {
console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>
<div></div>
I am trying to figure out why I get an error when I console.log a message on window resize in this jQuery plugin. Can I not reference the window from within the Plugin prototype?
;(function ( $, window, document, undefined ) {
"use strict";
var pluginName = "rigallery",
defaults = {
transition: "ease"
};
function Plugin ( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
this.getHeight();
},
getHeight: function() {
$(window).resize(function() {
console.log('Yay!');
});
}
};
$.fn[ pluginName ] = function( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
return this;
};
})( jQuery, window, document );
Okay, I figured it out. I moved the window.resize call to the init method, and then added a var that = this and then called the getHeight using that.getHeight(). I would be interested to know if this is the correct way to do this.
;(function ( $, window, document, undefined ) {
"use strict";
var pluginName = "rigallery",
defaults = {
transition: "ease"
};
function Plugin ( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var that = this;
this.createGallery();
this.slidesTransition();
$(window).resize(function() {
console.log(that.getHeight());
});
},
getHeight: function() {
var height = $(this.element).find("li:first img").height();
return height;
}
};
$.fn[ pluginName ] = function( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
return this;
};
})( jQuery, window, document );
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How would you change this kind of code?
How would I pass these variables in to options through jQuery, so that when the user uses the plugin, they must initialize the plugin from the HTML like so:
<script>
$('.elem').pluginName({
theme: 'blue',
animSpeed: 200
});
</script>
Here's my jQuery code. Pretty messy, but have a look. How could I change the variables to options?
$(function () {
var theme = "sunburst";
var btnColor = "yellow";
var icon = "power";
var message = "Hello World";
var animSpeed = 300;
var animType = 'fadeIn';
var btnText = "Purchase";
var btnLink = 'http://www.google.com';
var closeStyle = "dark";
var content =
'<div id="mn_close" class="' + closeStyle + '"></div>' +
'<div id="mn_border"></div>' +
'<i class="icon-' + icon + '"></i>' +
'<span class="mn_message">' + message + '</span>';
// '' + btnText + '';
$("#mn_close").live("click", function () {
$('.mn_bar').animate({
height: '0'
}, animSpeed, function () {});
});
var mn_bar = $(".mn_bar");
mn_bar.append(content);
$(function () {
mn_bar.addClass("animated");
mn_bar.addClass(animType);
mn_bar.addClass(theme)
});
});
Or here is the jsfiddle. http://jsfiddle.net/LwGRV/6/
I've being trying to implement the code in to this standard type of jQuery code too, but failing to merge:
;(function ( $, window, document, undefined ) {
var pluginName = "defaultPluginName",
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
},
yourOtherFunction: function(el, options) {
// some logic
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
Many thanks in advance if anyone can shed some light on to this.
You should have a look at this: http://api.jquery.com/jQuery.extend/
Your variables should be stored within an object.
I got a simple plugin as below:
$.fn.ajaxSubmit = function(options){
var submisable = true;
}
I want to able to change/access the variable myvar from outside the plugin, by doing something like below:
$(function(){
$('form').ajaxSubmit();
$('div').click(function(){
submisable =false;
});
});
You can also create methods to access the variables that are inside a plug in:
$.fn.ajaxSubmit = function(options){
var submisable = true;
$.fn.ajaxSubmit.setSubmissable = function(val){
submisable = val;
}
}
Then you can call it like this.
$('form').ajaxSubmit();
$('form').ajaxSubmit.setSubmissable(false);
This solution is not straight forward, but follows the jquery plugin guidelines.
(function($) {
var myVar = "Hi";
var methods = {
init: function(option) {
return this.each(function() {
$(this).data("test", myVar);
});
},
showMessage: function() {
return this.each(function() {
alert($(this).data("test"));
});
},
setVar: function(msg) {
return this.each(function() {
$(this).data("test", msg);
});
},
doSomething: function() {
//perform your action here
}
}
$.fn.Test = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.Test');
}
};
})(jQuery);
$("form").Test("init");
$("#getCol").click(function() {
$("form").Test("setVar", "Hello World").Test("showMessage");
});
Are you thinking to access them as properties? Something like:
$.fn.ajaxSubmit = function(options) {
var defaults = {},
o = $.extend({}, defaults, options);
var _myvar = 'blue'
this.myvar = new function(){
return _myvar;
}
this.setmyvar = function(_input){
_myvar = _input
}
return this.each(function() {
if (_myvar == 'blue') {
alert('hi');
}
if (_myvar == 'red') {
alert('bye');
}
});
}
And set like:
this.setmyvar('red');