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.
Related
I have some questions regarding memory leaks.
Please take a look at this block of code:
(function ($) {
$.fn.bnftWindow = function (options) {
// Default Settings
var settings = $.extend({
}, options);
// Validate parameters
if (settings.id === undefined || settings.id === null || settings.id === "") {
throw "bnftWindow id option is undefined, null or empty string";
}
// If window container div already exists
if ($("#" + settings.id).length) {
alert("bnftWindow id already exists - will be destroyed and recreated");
// destroy window container div
$("#" + settings.id).remove();
}
// create window container div
$("body").append("<div id='" + settings.id + "'></div>");
var currentInstance = $("#" + settings.id);
return currentInstance.each(function () {
currentInstance.data("bnftWindow", currentInstance);
var widgetId = currentInstance[0].id; //The id of the html element used to create the bnft widget
// Apply settings
$('#' + widgetId).kendoWindow(
settings
);
var dialog = $('#' + widgetId).data("kendoWindow");
currentInstance.destroy = function () {
kendo.destroy($("#" + widgetId));
$("#" + settings.id).remove();
}
});
function onRefresh(e) {
// Always center window first
if (settings.refresh !== undefined) {
settings.refresh(e);
}
var dialog = $("#" + settings.id).data("kendoWindow");
dialog.center();
}
};
}(jQuery));
And this block of code:
function Test()
{
var element = $("#myElement");
element.hide();
var that = this;
this.ids = {
grid: "messagesGrid",
gridButton: "gridButton",
composeWnd: "composeWnd"
};
this.grid = null; // will store the grid later
$("#" + this.ids.gridButton).on("click", function () {
try {
// Do something....
that.init();
}
}
catch (ex) {
alert("Error: " + ex);
}
});
}
Test.prototype.init = function()
{
// Do something else...
var that = this;
setTimeout(function() {
that.createWidget();
}, 500);
}
Test.prototype.createWidget = function()
{
// Do something else...
$("#grid").kendoGrid({ // Some properties here });
// store grid
this.grid = $("#grid").data("kendoGrid");
// Blah blah blah
}
Do the variables currentInstance, widget id, dialog, element, that, this.grid or the event handler causing memory leaks?
If element variable is causing a memory leak, is $("#myElement").hide(); the solution? (besides setting element variable to null after hide).
Thank you in advance.
The following works for me to clean up dialog instances:
_create: function () {
var that = this;
...
that.frmElement = that.wrapper.kendoWindow({
...
close: function (e) {
this.destroy();
that.wrapper.remove("#" + that.options.dialogId);
that.wrapper.empty();
}
...
}).data("kendoWindow");
}
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 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 );
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/
I am new to javascript I have a doubt in changing onclick event to mouseover please help
<script>
$(document).ready(function() {
(function ($) {
$.fn.readmore = function (settings) {
var opts = $.extend({}, $.fn.readmore.defaults, settings);
this.each(function () {
$(this).data("opts", opts);
if ($(this).html().length > opts.substr_len) {
abridge($(this));
linkage($(this));
}
});
function linkage(elem) {
elem.append(elem.data("opts").more_link);
elem.children(".more").click( function () {
$(this).hide();
$(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").animate({'opacity' : 'toggle'},1000);
});
}
function abridge(elem) {
var opts = elem.data("opts");
var txt = elem.html();
var len = opts.substr_len;
var dots = "<span>" + opts.ellipses + "</span>";
var charAtLen = txt.substr(len, 1);
while (len < txt.length && !/\s/.test(charAtLen)) {
len++;
charAtLen = txt.substr(len, 1);
}
var shown = txt.substring(0, len) + dots;
var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
elem.html(shown + hidden);
}
return this;
};
$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '<a class="more">Read More</a>'
};
})(jQuery);
$(function(){
$('.des_details').readmore({ substr_len: 150 });
});
});
</script>
Any suggestions?
There's a bit of API doc about .hover() which explains what I think you're trying to do. Hope this helps.
http://api.jquery.com/hover/
where you have
elem.children(".more").click( function ()
replace it with
elem.children(".more").hover( function ()
Try this code
$(urid).trigger('mouseover');