Passing Options into Your Plugin - J Query

Your first plugin adds a method to jQuery. However, there are a few options that would be helpful to others if they were exposed properly. What is the best method of passing options into a custom method?


Options are best passed into your custom plugin method via an options object. Using a single options object to pass in parameters promotes cleaner code, is easier to work with, and provides flexibility down the road.
When allowing options to be utilized in your plugin, it’s wise to provide sensible defaults.After providing sensible default options, it’s also important that your plugin provide a method for the user of the plugin to override the defaults. Both of these goals are easily accomplished by declaring a default options object, overriding the default options with user-supplied options and the jQuery extend() method, and then utilizing the options in your code:

By specifying option defaults, developers using your plugin have the ability to provide as many or as few options when they call your function. It is important to place your options’ defaults after you’ve defined your plugin entry method; otherwise, you will encounter an error:

Lastly, by specifying your options as an object attached as a child to your plugin function,the default options may be overridden only once in a project. A developer then has the ability to specify their own set of default options, minimizing the amount of code required to produce the desired behavior:


Supporting options in your plugin is a powerful way to add tremendous flexibility to the plugin. Plugins that support a rich set of options are more likely to fit the needs of a wider audience, perform a wider variety of tasks, and generally gain more popularity than plugins that don’t support options.
Including a set of default options with your plugin is another way to give developers who use your plugin flexibility and choice in how the plugin is implemented. A handy side benefit is that the plugin can always rely on certain options being defined, reducing the amount of code required to check whether an option has been passed. This leaves plugin users with the ability to override a single option, multiple options, or even all of the options every time they call your plugin. Lastly, by attaching the default options to the jQuery object, the options can be overridden globally, giving your users another tool to leverage in new and creative ways.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics