Click here to Skip to main content
15,886,362 members
Articles / jQuery

Get Started With Writing Your Own jQuery PLUGIN in a Simple Way

Rate me:
Please Sign up or sign in to vote.
3.86/5 (3 votes)
27 Apr 2018CPOL9 min read 10.8K   3  
Get started with writing your own jQuery PLUGIN in simple way

You might have worked on projects where you had to make use of third party plugins such as timeline.min.js, autoComplete.min.js to fulfill the project’s requirements. These plugins are developed by some other developers. Most developers would not think much about developing their own custom jQuery Plugin and just focus on making use of available third party Plugin. This is a good approach in order to finish the project on time and satisfy the clients.

Imagine! What if you could develop such reusable jquery Plugin and make use of that Plugin in more than one project which will have similar requirements? That sounds cool, isn’t it?

Yes! Now let me start with a theory to make you understand when you can take a decision to write plugin. Let us consider a most popular jquery plugin jquery.autoSuggest.js. You might have used this plugin in multiple projects. It does Ajax call to the server and displays data in a beautiful way. You might have used the same plugin for different purposes such as displaying user names on one page and displaying some other data in a similar fashion in another page of the same project. Here, the common thing among two pages which you can observe is RE-USABILITY.

Similarly, you can write such reusable jquery functions to make use in different pages/projects for similar functionality. This can be achieved through writing jquery plugin.

What is jQuery Plugin?

A jQuery plugin is a JavaScript file (.js extension) which contains related methods which can be used along with methods of jquery library.

If you are familiar with jquery, you might have written such code, e.g.:
$(“#Some_ID”).autoComplete({Some parameters and other information needed to make use of this plugin method name});

The above snippet is to make use of jQuery.autocomplete.js plugin:

In a similar way, you can create your own jquery plugin and make use of it in a similar fashion, e.g.: $(“#some_ID”).myNewPlugin({required parameters, information for the plugin});

In the above snippet, myNewPlugin is a jquery method in jquery. myNewPlugin.js which is going to be created by us in simple steps.

  1. Create a file with name jquery.myNewPlugin.js (the extension of the file should be .js):

    Image 1

  2. Write the following lines of the code in the file. I will explain each and every line of the code:

    Image 2

    The above code snippet is the syntax to write the plugin. We need to write our plugin methods within those two lines of code due to one of the major concerns. Let me explain about those two lines of code in detail:

    • At the beginning, you can see the semi colon. We don’t need to add semicolon in our plugin but it is recommended to add semicolon because jquery plugin is nothing but a separate method written in a JavaScript file. Suppose you are working in a team and one of the developers didn’t put semicolon at the end of methods which he has written to achieve some functionality on the same page where you are going to make use of this plugin. In that scenario, your plugin may not work as expected. Sometimes, it will not call your plugin method name even though the code which you have written in the plugin is perfectly fine. So in order to avoid such issues, better use semicolon at the beginning
    • The above two lines of code are written because of creating scope for methods which we will write in the plugin file and to protect $ alias. Within the function there, you can see dollar ($) variable as parameter. $ is a very famous variable among JavaScript libraries. It is always assumed that $ is the alias for jQuery function. So if we use other plugins and expect our plugin to work well with them and still use $ as alias for jQuery function, then we need to put all of our jquery methods which we are going to write for our plugin inside of a function by passing the jQuery function after closing the curly bracket of that function and pass $ as parameter to the function.
  3. Within those two lines of code, we need to write our jquery plugin. Remember, in general, a jquery plugin is nothing but a reusable jquery METHOD.

    Image 3

    In line number 5, you can see the syntax of plugin method. $ is alias for jQuery function, fn represents that it is a FUNCTION and myNewPLugin is the method name which is our plugin. This is the syntax to start with jquery plugin. Usually, you define a function as shown below:

    Image 4

But in our case, you write in a different way, as shown below:

Image 5

It gives a clear idea that we can pass the parameters to our method, right? Exactly!! We can even pass parameters to our plugin. It would look like shown below:

Image 6

In the above screenshot, you can see that there are two parameters such as firstname, lastName. This is awesome, isn’t it? Okay ... I hope you have got my points which I have been explaining till here. Now it is not yet done!

Let me put an alert box inside the plugin method:

Image 7

So, it is not yet done. Now let us test this by adding an alert box inside the plugin method and check whether this works properly or not. I have added an alert message and my code looks like this:

Image 8

How do you use any jquery plugins in your solution? It is simple. You create an HTML page and give the reference of that third party plugin, right? We will do the same thing.

Note: We are writing JQUERY plugin. That means we need to add jquery.js library reference in our HTML page before adding our plugin reference on that page. Because our plugin makes use of jquery.js library’s methods and variables such as $, jQuery, etc.

  • Here, I will use Visual Studio. I will add my plugin file under the script folder and add this custom plugin reference on the page PluginTest.html. In the previous steps, I used sublime editor. You can directly use Visual Studio for all the steps which I have explained earlier.

    Image 9

    Inside the body tag, I have created one div and added an ID to it. There is a reason for it. We need a reference on page on which we initiate the call for plugin method. In simple words, suppose you have to call autosearch on textbox. You will make use of autosearch plugin and call the plugin method on the TEXTBOX from where you wanted to initiate search functionality. Here, the textbox is the place from which we call autosearch plugin. Usually, we use ID of the textbox as reference on which we call autosearch plugin.

In a similar way, in our example, I have used an ID of a div on which I will call my plugin.

  • In the PluginTest.html file, I will initiate ready event on document under the script tag:

    Image 10

     

  • Now call the plugin under the ready event:

    Image 11

     

  • Now execute the code by pressing F5:

    Image 12

Ok ... We have completed the first step of writing jquery plugin. Again, this is only the beginning !!.. We need to pass some parameters to our plugin, isn’t it? Because plugin itself refers that it is a REUSABLE code. In that sense, there can be different values we may need to pass with respect to different scenarios on similar functionality. Let’s begin with how to pass parameters.

Let me pass two parameters. First name: Pradeepa, last name: Achar. Now both the code would look as shown below:

Image 13

Image 14

And the output would be:

Image 15

As a best practice, we need to return the node after the execution of jquery plugin:

Image 16

NOTE

It's important to use each loop because our typical jQuery object will contain references to any number of DOM elements. If you want to manipulate specific element, then you must need each loop. So your code must always contain the following code:

Image 17

Inside the loop, I have created a variable and storing current jquery object($(this)). This object will have reference to the element from which we have called this plugin. In our case, the div element’s id mainPanel. Check the Plugintest.html file for the reference. That element can have class, any attributes. It can be accessed through this object.

Now let us move on with some advanced concepts. Since plugin is a reusable code, it accepts parameter values. If we use this plugin in different pages, then the parameter values may vary from page to page depending on the requirement. As a good programmer, you need to assign some default value and override those default values with new values through parameters in different pages in which this plugin is going to be used. This is cool... isn’t it?

Let our code look like shown below:

  • Let us create default variables and assign default values:

    Image 18

  • There can be many parameters. In that case, if we pass multiple parameters to function, it is not a good idea. Rather, let’s keep all of the parameters in an object. So code will be changed as shown below:

    Image 19

In the above code snippet, observe that I am passing an object options and rather than declaring variables separately, I have kept them under an object defaults.

Defaults object’s variables have default value, empty string. You can even declare numeric, boolean as per your requirements. Now we need to assign new values from the page where we are going to use this plugin. This assignment is achieved through the following syntax:

Image 20

In the above code snippet, you can see var opts=$.extend(defaults,options); Here, it will assign new values from options object to defaults objects. The new values will be in the object opts.

Now we need to learn how to pass values to the plugin and how to make use in the plugin.

  1. If there are more than one parameters, then it has to be passed as object or individual parameter as follows. In our example, we are passing parameter values from testPlugin.html page:

    Image 21

    In the above code snippet, we are passing values within flower brackets and as key-value pair. The key is the variable name declared in the defaults object in the plugin. Each key-value pair is separated by comma. Observe the code snippet again.The key variable’s name in the parameter should be the exact name of the variable declared in the plugin as shown below:

    Image 22

Okay. We are all set to complete the basics of writing jquery plugin. Remember one thing, you are going to write methods in the return this.each loop. Suppose you have to create an HTML layout and perform some other actions, then your code should be like this as shown below:

Image 23

In the above code snippet, I am calling method createHTML by passing the reference element whose id is mainpanel which is created in the testPlugin.html page.

You can define some more methods in the plugin and call them whenever it is required .

Image 24

Ok. We are all set to write custom jquery plugin now. Happy coding and teaching!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --