jQuery plugin not overriding defaults - javascript

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);

Related

Write a jquery plugin to open a link in new window

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.

How can I override few parameter of plugin without editing it

Want to override few parameter of plugin without editing it. link for plugin https://www.o2.co.uk/shop/homepage/images/shop15/carousel/js/carousel.jquery.js Can we add another script to override above script object parameter such as displayTime to 1000 & autoStart to false. . I tried $.extend(). but failed. I don't want to make changes in current plugin
<script>
(function($,document,undefined) {
$.fn.carousel = function(opts) {
var options = {
'displayTime': 5000,
'autoStart': true
};
<----code --->
}
</script>
You could replace it with a function of your own:
var oldCarousel = $.fn.carousel; // Need a reference to the original
$.fn.carousel = function(opts) {
var options = {
// set your personal defaults here
};
if (opts) {
$.extend(options, opts);
}
return oldCarousel.call(this, opts);
};

jQuery plugin - update settings after initialization

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>

Creating a jQuery callback function

I have problem understanding how to create a callback function which I can use to extend the options, as stated in this guide. Here's the excerpt of code that I want to use for callback;
var chart = {};
chart.data = $('.liselected').attr("data");
chart.command = $('.liselected').attr("cmd");
chart.option = "option"; // Category of event request
chart.sessionid = docCookies.getItem("sessionid");
chart.ageType = selectedAgeType;
chart.showData = showUnderlyingData;
var action = function(result, status) {
$('#thumbnails .error').remove();
var chart_list = "";
$.each(result, function(i, val){
chart_list += //Custom HTML Output
});
$('#chart_view').html(chart_list);
};
$.post("jsoncommand", JSON.stringify(chart), action);
So that I can call using $("a").on("click", postcommand(eventrequest)), I tried creating a function like this;
$.fn.postcommand = function(){
var settings = $.extend({
item : {},
data : $('.liselected').attr("data"),
command : $('.liselected').attr("cmd"),
option : "specify query",
sessionid : docCookies.getItem("sessionid"),
ageType : selectedAgeType,
showData : showUnderlyingData,
}, options );
return //How do I make the output of HTML result is customizable?
};
But of course, my attempt is a failure. Spoon feeding is good, but you can always give me a hint and I'll try to explore on my own. Thanks!
It might be a good idea to check out the jQuery plugin section: http://learn.jquery.com/plugins/advanced-plugin-concepts/. You could do something like this:
$.fn.postcommand = function (options) {
// define some default values for your plugin
var default = {
callback: function () {}
}
// merge default settings, with the ones given
var settings = $.extend( {}, defaults, options );
return this.each(function() {
var $this = $(this);
$this.on('click', function(event) {
settings.callback();
event.preventDefault();
});
}
});
And then use your plugin on some links:
$('a.useCallback').postcommand();

Writing jquery plugin and it is not executing

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.

Categories