I've made a jQuery plugin and it works pretty much ok. Except that when I have multiple instances on the same page the last instance's options/settings are used for both.
Here's a stripped down version of it... sorry for the length.
(function() {
var settings = {};
var defaults = {
duration : 1000,
easingShow : 'easeOutBounce',
easingHide : 'easeOutQuad'
};
var methods = {
init : function(options) {
return this.each(function(n) {
settings = $.extend(defaults, options);
});
},
show : function() {
// settings used here
},
hide : function() {
// also used here
}
};
$.fn.expander = 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 {
$.error('Method ' + method + ' does not exist on jQuery.expander');
}
};
})(jQuery);
I'm sure it's some kind of namespace issue, as I get confused by that often.
Thanks
use
settings = $.extend(true, {}, defaults, options);
from jquery docs @ http://api.jquery.com/jQuery.extend/
deep If true, the merge becomes recursive (aka. deep copy). target The object to extend. It will receive the new properties. object1 An object containing additional properties to merge in. objectN Additional objects containing properties to merge in.
Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target.
To have different settings per element, you can store them at each element using .data()
Check out a working demo: http://jsfiddle.net/roberkules/XvKs8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With