I've written a simple jQuery plugin, but I'd like to make it more advanced so I can do things like:
$.myplugin.close();
$.myplugin.open();
$.myplugin.next();
$.myplugin.prev();
How can I write a plugin that can be called like this?
-------------------------Updated-------------------------
Thanks @Craig MacGregor, appreciate it.
But to call the function it need to be like below
$(this).myplugin.load();
You can assign an object to "myplugin" like so:
$.myplugin = {
close: function(){
//code
},
open: function(){
//code
},
next: function(){
//code
},
prev: function(){
//code
}
};
Just An Example:
(funciton($) {
var methods = {
init: function() {},
close: function() {},
open: function() {},
prev: function() {},
next: function() {},
};
$.fn.myplugin = function (method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on myplugin' );
}
};
}(jQuery));
//usage
$(selector).myplugin();
// call methods
$(selector).myplugin('close');
$(selector).myplugin('open');
$(selector).myplugin('next');
$(selector).myplugin('prev');
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