Writing Your First jQuery Plugin - J Query

Problem
You’ve decided that you want to write a jQuery plugin. How do you write a plugin in jQuery? What best practices should you follow?

Solution

jQuery is designed to make writing a plugin very simple and straightforward. You can extend the existing jQuery object by writing either methods or functions. Simply declaring the following JavaScript after inclusion of the jQuery core library will allow your code to use your new custom method or function.

Writing a custom jQuery method

jQuery methods are available to be chained and thus can take advantage of jQuery selectors. jQuery methods are defined by extending the jQuery.fn object with your method name. Because the jQuery object must be able to handle multiple results, you must wrap your custom functionality inside a call to the each() function to apply your code to all of the results:


Accessing this new plugin is as simple as calling jQuery like you normally would and utilizing your new method name:

Writing a custom jQuery function

Functions are attached to the main jQuery object. Functions are designed to be called outside of a jQuery selection:

This new function can be manipulated and called normally:

Discussion

Attaching new methods and functions to the main jQuery object are a powerful feature of jQuery. Many of the core methods are built into the library using this same technique.
By leveraging this existing foundation in jQuery, users of jQuery and users of your plugin have a fast and concise way to add new functionality, extend existing functionality,and mold the jQuery code into whatever form suits them best. This flexibility is a key feature and enables jQuery and its plugins to be used by a wider audience.
The choice to extend jQuery via a new method or a function mainly depends on the needs of the developer. In general, focusing on extending jQuery via adding a new method is best because this allows that new method to be chained along with other methods, and it allows the code in the method to take advantage of jQuery’s selector engine.


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

J Query Topics