I have wrote this plugin to open link to new window but does not work
any idea what might have gone wrong?
(function( $ ) {
$.fn.myPlugin = function() {
var defaults = {
width: 800,
height: 700,
scrollbars: 1,
location: 1,
status: 1
},
self = this,
opts = $.extend(defaults, options);
this.filter('a').click(function() {
$("a").attr("target","_self");
window.open($(this).attr('href'),'title', opts);
return this;
});
};
}( jQuery ));
$('a').myPlugin();
Instead this
opts = $.extend(defaults, options);
this.filter('a').click(function() {
$("a").attr("target","_self");
window.open($(this).attr('href'),'title', opts);
return this;
});
try:
opts = $.extend({}, defaults, options);
$('a').click(function(){
window.open($(this).attr('href'),'title', opts);
});
Here you can find examples of using window.open(). Also read doc:
Keep in mind that the target object (first argument) will be modified,
and will also be returned from $.extend(). If, however, you want to
preserve both of the original objects, you can do so by passing an
empty object as the target:
var object = $.extend({}, object1, object2);
Hope this help you.
I think you are missing the options declatarion variable that you had in the extend function, the second paramater hasn't been defined.
(function( $ ) {
$.fn.myPlugin = function() {
var defaults = {
width: 800,
height: 700,
scrollbars: 1,
location: 1,
status: 1
},
options, //<-------- This one right here !
self = this,
opts = $.extend(defaults, options);
this.filter('a').click(function() {
$("a").attr("target","_self");
window.open($(this).attr('href'),'title', opts);
return this;
});
};
}( jQuery ));
$('a').myPlugin();
Good luck with the rest of the code.
Leo.
Related
I have found nice jQuery plugin and it uses boiler plate template. Everything works fine, but I can't invoke internal function to get selected items.
The construction of this plugin is below:
(function ($, window, document) {
'use strict';
// constructor
var SearchableOptionList = function ($element, options) {
this.$originalElement = $element;
this.options = options;
this.metadata = this.$originalElement.data('sol-options');
};
// plugin prototype
SearchableOptionList.prototype = {
DATA_KEY: 'sol-element',
// default option values
defaults: {
...
},
// initialize the plugin
init: function () {
this.config = $.extend(true, {}, this.defaults, this.options, this.metadata);
...
return this;
},
//some functions
...
selectAll: function () {
...
},
deselectAll: function () {
...
},
getSelection: function () {
return this.$selection.find('input:checked');
}
};
// jquery plugin boiler plate code
SearchableOptionList.defaults = SearchableOptionList.prototype.defaults;
window.SearchableOptionList = SearchableOptionList;
$.fn.searchableOptionList = function (options) {
var result = [];
this.each(function () {
var $this = $(this),
$alreadyInitializedSol = $this.data(SearchableOptionList.prototype.DATA_KEY);
if ($alreadyInitializedSol) {
result.push($alreadyInitializedSol);
} else {
var newSol = new SearchableOptionList($this, options);
result.push(newSol);
setTimeout(function() {
newSol.init();
}, 0);
}
});
if (result.length === 1) {
return result[0];
}
return result;
};
}(jQuery, window, document));
Full code you can find on GitHub.
I try to invoke getSelection function like below:
// initialize sol
var s = $('#my-select').searchableOptionList({
maxHeight: '150px',
showSelectAll: true
});
s.selectAll();
I get an error:
TypeError: this.config is undefined
Is it possible to invoke functions using this template of boiler plate?
You can play around on jsfiddle
I believe line 1031 is the culprit
setTimeout(function() {
newSol.init();
}, 0);
Since the init is deferred the code is not ready when you call it right away. The esiest fix is to defer your call too, but there is no gurantee that it will be initialized.
setTimeout(function(){s.selectAll()},1000);
The better solution is to use the plugin's events to hook into when it has been initialized.
$('#my-select').searchableOptionList({
maxHeight: '150px',
events: {
onInitialized: function() {
this.selectAll();
}
}
});
fiddle
I have a jQuery plugin, and I want to be able to change options on the fly, like this example: $('.element').pwstabs('options','effect',scale) or something simular to it. I tried adding update: function, tried adding Plugin.prototype.update, but still cant figure out how to do that :)
Here's the structure of the plugin:
;(function ($, window, document, undefined) {
var pluginName = "pwstabs",
defaults = {
effect: 'scaleout',
defaultTab: 1,
containerWidth: '100%',
tabsPosition: 'horizontal',
horizontalPosition: 'top',
verticalPosition: 'left',
responsive: false,
theme: '',
rtl: false,
controlls: false,
next: '',
prev: '',
first: '',
last: '',
auto: false,
play: '',
pause: ''
};
function Plugin(element, options) {
this.element = $(element);
this.$elem = $(this.element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function(){
// Here's the code for the plugin
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
new Plugin( this, options );
});
};
})(jQuery, window, document);
So now I use the plugin like:
$('.element').pwstabs({
effect: 'scalein',
defaultTab: 2
});
And when I click a button, i want to change effect to lets say scaleout. With code like:
$('.button').click(function(){
$('.element').pwstabs('options','effect','scalein');
});
So how do I implement this in the plugin?
Currently the only supported invocation pattern in that plugin is to send in an object literal containing the settings to overwrite the defaults. E.g.:
$('.element').pwstabs({
effect: 'scalein',
defaultTab: 2
});
That invocation pattern is defined in the following method:
$.fn[pluginName] = function ( options ) {
return this.each(function () {
new Plugin( this, options );
});
};
As you see, a dictionary of options is sent as the only parameter to the constructor function Plugin() to build the plugin and initialize it.
To support the invocation pattern you need, you would have to modify this method to support both invocation patterns (initialization with an object literal, but also invoking any method with more params, like your options setting method).
Here is an improved function that will handle both invocation patterns. In addition it will also store the instance of a plugin on an element, so you can access the existing settings etc. on subsequent invocations (e.g. settings changes) on the same element.
$.fn[pluginName] = function (options) {
// get the arguments
var args = $.makeArray(arguments),
after = args.slice(1);
return this.each(function () {
// check if there is an existing instance related to element
var instance = $.data(this, pluginName);
if (instance) {
if (instance[options]) {
instance[options].apply(instance, after);
} else {
$.error('Method ' + options + ' does not exist on Plugin');
}
} else {
// create the plugin
var plugin = new Plugin(this, options);
// Store the plugin instance on the element
$.data(this, pluginName, plugin);
return plugin;
}
});
}
This would allow you to invoke the plugin as requested:
$('.element').pwstabs('options','effect','slidedown');
However, this implies you have an 'options' method in the Plugin prototype, so make sure to add one:
Plugin.prototype = {
options: function (option, val) {
this.settings[option] = val;
},
// Constructing Tabs Plugin
init: function () {
// omitted code for brevity
}
}
As you see the options settings just sets the new option on the existing instance. Very simple and efficient. The new setting will be picked up by the click method handler and voila!
Here is a jsFiddle with example code in case you have trouble implementing what i was describing so far:
http://jsfiddle.net/7whs3u1n/6/
Update: I have much improved my answer to get rid of unneeded stuff, include more details and a full implementation that works (check the fiddle above) ;) i hope that this answers your question!
Adding statefulness to your plugin wasn't hard, but when you have spare time also check the alternative mechanism for writing stateful jQuery stateful plugins called jQuery widget factory:
http://learn.jquery.com/plugins/stateful-plugins-with-widget-factory/
In the future you can consider rewriting your plugin to use the widget factory. It would certainly make your code simpler ;)
Try this pattern
(function ($) {
var defaults = {
"text": "abcdefg",
}
, options = $.extend({}, defaults, options);
$.fn.plugin = function (options) {
var options = (function (opts, def) {
var _opts = {};
if (typeof opts[0] !== "object") {
_opts[opts[0]] = opts[1];
};
return opts.length === 0
? def
: typeof opts[0] === "object"
? opts[0] : _opts
}([].slice.call(arguments), defaults));
return $(this).text(options.text)
}
}(jQuery));
$(".results:eq(0)").plugin(); // return `defaults`
$(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
$(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
(function ($) {
var defaults = {
"text": "abcdefg",
}
, options = $.extend({}, defaults, options);
$.fn.plugin = function (options) {
var options = (function (opts, def) {
var _opts = {};
if (typeof opts[0] !== "object") {
_opts[opts[0]] = opts[1];
};
return opts.length === 0
? def
: typeof opts[0] === "object"
? opts[0] : _opts
}([].slice.call(arguments), defaults));
return $(this).text(options.text)
}
}(jQuery));
$(".results:eq(0)").plugin(); // return `defaults`
$(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
$(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="results"></div><br />
<div class="results"></div><br />
<div class="results"></div>
I am trying to write a simple jQuery plugin for my needs, using a variant of the first one in this style guide.
;(function($) {
var plugin_name = 'my_plugin',
defaults = {};
function Plugin ( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = plugin_name;
this.init();
}
Plugin.prototype = {
init: function () {
// Plugin code - attempt to debug
alert('hi');
}
}
$.fn[plugin_name] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + plugin_name)) {
$.data(this, 'plugin_' + plugin_name, new Plugin( this, options ));
}
})
}
})( jQuery );
However, it doesn't seem to be executed when I call it. Fiddle here: http://jsfiddle.net/DCRnU/
$(document).ready(function() {
$.fn.my_plugin();
});
What am I missing out on?
You're not calling the function properly.
If you had a div element in your HTML, you could call your function like this:
$(document).ready(function() {
$("div").my_plugin();
});
Example fiddle
That's because this line: return this.each
It's expect to get some iterable object.
But there is nothing to loop over it.
if you add something like this:
var array = [1];
$(array).my_plugin();
it'll be fine.
I have a basic plugin that populates an array within the plugin. How can I get that array via a method call with parameters. This is my first plugin so please go easy on me if this is a dumb question.
basic Plugin
(function($) {
$.fn.myPlugin = function() {
return this.each(function(){
tagArray = []; // my array that is populated
//code that does stuff to populate array
});
}
})(jQuery);
I would like to get the tagArray like so...
var arr = $('.className').myPlugin("getArray");
Where I can then use that array elsewhere. How can I accomplish this?
Thank you for any help.
I don't see why you would need the "getArray" parameter. In any case you need to define only 1 array and make your function return it:
(function($) {
$.fn.myPlugin = function() {
var tagArray = [];
this.each(function(){
// add something to tagArray
});
return tagArray;
}
})(jQuery);
That's a rather strange requirement, but an easy way to do that if there is only parameter would be something like :
(function($) {
$.fn.myPlugin = function(param) {
var tagArray = [],
elems = this.each(function(){
tagArray.push( $(this).text() ); // whatever you do ??
});
return param == 'getArray' ? tagArray : elems;
} // ^^ if the parameter is passed, return the array, otherwise the elems
})(jQuery);
FIDDLE
It's a bit hackish, but it works. You could also just return this.map(function() {... to always return an array etc, or read up on how to pass multiple parameters to a plugin and do different things etc. instead of the hardcoded check for 'getArray' used above.
Try
(function($) {
function Plugin($el, opts){
this.tagArray = [];
this.tagArray.push($el.attr('id')) //for testing the retuned instance
$el.data('myPlugin', this);
}
Plugin.prototype.getTagArray = function(){
return this.tagArray;
}
$.fn.myPlugin = function(opts) {
if($.type(opts) == 'string'){
var plugin = this.data('myPlugin');
return plugin[opts]();
}
return this.each(function(){
var $this = $(this);
new Plugin($this);
});
}
})(jQuery);
jQuery(function(){
$('#e1, #e2, #e3').myPlugin();
console.log($('#e1').myPlugin('getTagArray'))
console.log($('#e2').myPlugin('getTagArray'))
console.log($('#e3, #e1').myPlugin('getTagArray'))
})
Demo: Fiddle
I just finished writing a JQuery Plugin myself and here is the basic structure I settled on:
(function (window, document, $, undefined) {
//Local Methods
var methods = {
init : function(options){
//stuff you want to do when your plugin initializes i.e. when you do $('selector').myPlugin(options)
},
getArray: function(){
//your getArray method. Put your get array logic here
}
}
//Plugin Initialize
$.fn.myPlugin = function(args){
if ( methods[args] )
{
//execute JQuery Plugin Method
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
//Process JQuery Plugin Options
var opts = $.extend({}, $.fn.myPlugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist on myPlugin' );
}
};
//Define Default Options
$.fn.myPlugin.defaults = {
option_1: '',
option_2: '',
option_n: ''
}
//API Methods
var M = $.myPlugin = function(){};
$.extend(M, {
getArray: function(){
return methods.getArray();
}
});
}(window, document, jQuery));
Doing this allows you to start your plugin like this (as usual):
$('.className').myPlugin(options);
and/or call your getArray function like this:
$.myPlugin.getArray();
I hope this helps you get closer to where you want to be.
I'm working on a jQuery plugin and can't seem to override the default settings, here's a snippet of the plugin.
$.Auction = {
defaults: {
parentId: '#span',
bidButtonClassName: '.live_bid'
}
};
$.setAuction = function(options){
startAuction();
}
function startAuction(){
var options = $.extend({}, $.Auction.defaults, options);
alert(options.parentId);
}
$.setAuction({parentId: '#div'});
Basically I'm trying to override the parentId value at the bottom, but it always alerts the value #span. Any ideas what I'm doing wrong? Thanks!
You're passing {parentId: '#div'} as an argument to $.setAction, but you're not actually using it. You want to do something like this:
$.setAuction = function(options){
startAction(options);
}
function startAction(options){
options = $.extend({}, $.Auction.defaults, options);
alert(options.parentId);
}
Edit: #TmEllis suggests a better way of implementing this functionality, but it can be made better still by making the defaults themselves customizable:
(function($)
{
$.fn.setAuction = function(options)
{
options = $.extend({}, $.fn.setAuction.defaults, options);
return this.each(function()
{
alert($(this).id);
});
};
$.fn.setAuction.defaults =
{
bidButtonClassName: '.live_bid'
};
})(jQuery);
See this article for a more complete discussion of how to write good jQuery plugins.
I think you need to change the code a bit.
$.fn.setAuction would be better than $.setAuction (They do two different things)
as you could do:
$("#span").setAuction ({bidButtonClassName:"classname"});
and pass the element to it as a selector not as the plugin options (unless it needs to be in options)
Your plugin code might look something like then:
(function($) {
$.fn.setAuction = function(options) {
var defaults = {
bidButtonClassName: '.live_bid'
};
var options = $.extend(defaults, options);
//or to preserve defaults
var options = $.extend({}, defaults, options);
return this.each(function() {
obj = $(this); //"#span"
alert(obj.id);
});
};
})(jQuery);