JQuery Plugin Creation

Hi there,

I have been checking out the following sitepoint tutorial on creating a plugin using Jquery

I have some Questions about the selector and the parameters.
Say for example, I wanted to pass parameters into the plugin:


(function($) {
	// jQuery plugin definition
	$.fn.MyPlugin = function(params) {
             
         // do something
		return this;
	};
})(jQuery);

It is as simple as $(selector).MyPlugin(someparameters)

And conversely if the plugin takes no parameters $(selector).MyPlugin();

Firstly is my understanding correct and secondly what if the plugin doesn’t
require a selector? What if it doesn’t need to do anything to a given DOM element?

would it be something like:

$().MyPlugin(someparameters)

More or less you are correct, the most common way for passing parameters into a plugin is by using an object which you can merge if you wish to have defaults. See the below example:

(function($) {
    $.fn.myPlugin = function(options) {
        var defaults = {
            type : null,
            key  : false
        };
        
        $.extend(defaults, options);
    };
})(jQuery);

$('selector').myPlugin({
    type : 'select',
    key  : true
});

If you don’t wish to use a selector reference all you simply need to do is remove the fn extender from the new plugin declaration like the below example:

(function($) {
    $.myPlugin = function() {
        alert('foobar');
    };
})(jQuery);

$.myPlugin();

Thanks SgtLegend that really clears things up :wink: