Shortcuts with jQuery Plugins
 
 

You don't need to reinvent the wheel when you design your code. You don't even need to recreate the wheel. The "wheel" in this scenario is your jQuery code. Plenty of jQuery plugins perform the tasks that you need to do, so you don't need to write the code from scratch. The official jQuery site has several plugins that you can search through to find if what you need to code has already been done. If there isn't a plugin already made, you can create your own. This article discusses jQuery plugins and shows you how to make your own.

What is a Plugin?

 A plugin for jQuery is not much different than a plugin for any other application. A plugin is just a file or function that you can plug into any part of your code and use it to reduce coding time. It is dynamic and flexible enough where it can work with several sections of your code, but it usually has a specific output.

For instance, you could decide that you want to format a date with each jQuery string that can be converted to a date. Let's assume that jQuery does not have a plugin already made to perform this conversion. You can write your own jQuery plugin that can be inserted into each page of your code and used to perform the conversion and formatting for you. Instead of rewriting the same conversion code over and over, you just use your plugin function.

If you're used to programming in other languages, this type of coding is similar to basic functions or subroutines. A jQuery plugin is exactly that - a function that performs a task that you need to perform in several sections of your code. They provide several advantages. The first one is to minimize the amount of code that you write, which in turn reduces the time it takes you to design and code your applications.

You use jQuery functions similar to functions in other programs. The function must be accessible, so when you load the web page you must have the jQuery function either in the page code or stored in an external file. If you go the route of an external file, then you must include the jQuery file in the head section of the HTML code.

Since jQuery is just a framework of the JavaScript language, you include a jQuery plugin in the same way that you include another JavaScript file. The following HTML code is a standard, simple example of a plugin file included in the head section.

<!DOCTYPE html>

<html>

<head>

<script src="https://mysite.com/myfile.js"></script>

<script>

$(document).ready(function(){

        $("p").text("The plugin file was loaded.");

});

</script>

</head>

<body>

<p> </ p>

</body>

</html>

Notice that there isn't anything written to the HTML file until the page is loaded and ready to run jQuery functions. Notice that the first script tag points to a "myfile.js" external file. This is the file that contains our jQuery custom plugin. With the plugin included in the HTML headers, you can then use it in your code.

The script content simply writes "The plugin file was loaded" to the paragraph with the HTML DOM. This is not the function, but you will have a mix of your own jQuery code with some plugin functionality in your code. Just note that the two are different in terms of what happens when the jQuery function is called and what happens with your individual page code. Remember that plugins are just like functions and are there to perform a task that you need done continually in your project. Therefore, it's best to store your plugins in a separate file and insert it using the script tag.

Plugin Basics

Since you know that a jQuery plugin is just a function that can be called anywhere in your code, it makes sense that when you create a plugin you create a "function."

JQuery has the ".fn" statement that lets you add a custom function that ultimately acts as your plugin. Let's take a look at an example.

$.fn.showopentext = function() {

    this.text( "The page has successfully loaded." );

};

This plugin is simple just so that we can illustrate how you create your own plugins. Notice that we started with the ".fn" statement. This statement then has the "showopentext" statement appended to it after the period. The appended text is officially the name of your plugin. In this example, the plugin name is "showopentext." This is the name you'll use when you call the plugin in your pages.

The statements within the function are executed each time it's called. In this example, the only statement that executes places "The page has successfully loaded" in the element.

The following code shows you how to use the plugin.

$("#openingparagraph).showopentext();

That's it. The jQuery code references a container or paragraph element named "openingparagraph" and then the plugin is called. The plugin uses the "this" statement to indicate that you want to print the text to the current element passed to it.

There is one more expression we should add to the function. Right now, our plugin will work fine provided there are no other plugins with the same name installed. When you work with larger applications, you run into several plugins included in the application code. If you accidentally add a plugin that isn't compatible with yours, you can cause serious errors on your page.

You avoid this situation by enclosing your function in an immediately invoked function expression. This will stop your function from interfering with another and vice versa. Let's take our plugin and enclose it in one of these expressions.

(function($) {

$.fn.showopentext = function() {

    this.text( "The page has successfully loaded." );

};

}(jQuery));

Notice that now the custom plugin is enclosed with the immediately invoked function expression. Just remember that each time you create a plugin, you should enclose it within this expression to avoid compatibility issues with other plugins. Don't assume that it will never happen, because you can have dozens of plugins in one application, and it's tedious to find which two functions are incompatible once the application grows.

Creating Your First Plugin

We can incorporate the previous section's code into our very first plugin. For example, you might want to display a greeting to a logged in user. This is common when developers personalize their apps for registered users. You query an API or a database and request the user's first name (or you can store it to a cookie). The user's first name is then shown at the top of the window as a user friendly greeting to let the customer know that he is indeed logged in. We can use jQuery to accomplish this module for a web page.

First, let's take a look at the HTML for the registered user's home page.

<!DOCTYPE html>

<html>

<head>

<script src="https://mysite.com/myfile.js"></script>

<script>

// to be written after the plugin is complete

</script>

</head>

<body>

<p> </ p>

</body>

</html>

We've eliminated the JavaScript custom script to save it for when we complete our plugin. We don't know what we'll name our plugin yet, so this code should be written last. We have our script file included, so we know that the plugin will be stored to a file named myfile.js.

Our plugin will have two steps:

1) Query an API to get the user's first name.

2) Apply the result to the paragraph tag in the page.

Let's first write the function code that creates the plugin. 

(function($) {

$.fn.hellotext = function(custid) {

var json = {

    "custid": custid

};

$.ajax({

    type: "POST",

    url: "http://webservicesite.com/service.asmx",

    data: json,

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    success: function (data) {

                        this.text("Hello, " + data.customer)

            },

    failure: function (data) {

                        this.text("N/A");

            }

});

};

}(jQuery));

Notice we opened the code with the immediately invoked function expression and gave our custom function the name "hellotext." This again is important to avoid incompatibility with other plugins.  We have a JSON object that contains the customer's ID. We pass this customer ID to the function when we call it. The customer ID is assigned to the variable "custid" and then it's used to fill the JSON object with the customer that we want to query.

The AJAX section is the same as the previous section. We use a custom URL to query the web service and assume it takes JSON format as input. The way you pass data to a web service is up to the service developer, so make sure that you check the developer's documentation before you pass JSON formatted input. Some web services require text or even XML input.

If the query is successful, we use the "this" reference to indicate that we want to use the current element. This element can be anything including a div container, a paragraph, a span element, or even just the body of the DOM. Using "this" makes the plugin dynamic, so you can incorporate it into any HTML page regardless of the HTML tag used to display the user's name.

We have a success and failure function. The success function indicates that the query finished successfully and the data contains the customer's name in a field named "customer." Again, the API's documentation would tell you the name of the field that contains data, so you need to use this field with the "data" variable. We tell the jQuery code to print "Hello <name>" to the HTML page.

If the query fails, then we just print "N/A" to the element.

After you copy and paste this code to a text file, save it as "myfile.js" and make sure you save it to the root of your web application. If you recall in the HTML that we set up, we linked a file named myfile.js located in the root of the application directory. If you don't place the file in the right directory, your jQuery call to the function will give you an error and the user's name won't display.

With the plugin created and saved to your application's root directory, you can now go back to the HTML code and add the call to your plugin to display a user's name.

<!DOCTYPE html>

<html>

<head>

<script src="https://mysite.com/myfile.js"></script>

<script>

$(document).ready(function(){

    $("p").hellotext(22);

});

</script>

</head>

<body>

<p> </ p>

</body>

</html>

We added custom jQuery code to the script tags that calls the "hellotext" function. Notice that we pass the value "22" to the function. If you recall, the custom plugin takes a customer ID value to pass it to the AJAX call. It's required to get the cusotmer's information. We use a static value, but you can obtain this value in several ways. Since you won't have a static value to pass, you could have the customer ID from a cookie or the URL querystring. You could also have the customer ID stored in a session variable if the user is already logged in. Some developers query a database for this information and pass it to a custom function. The way you gain access to the customer ID is dependent on your application, the way you design your code, and the data you need locally.

When we pass the customer ID, the custom plugin queries the API for the customer and gets the user's name. It's then displays a welcome message to the user within the paragraph tags. Remember that we used the "this" statement, so you can call this function an any tag that supports the "text" method. For instance, the following HTML page would also work with your custom plugin.

<!DOCTYPE html>

<html>

<head>

<script src="https://mysite.com/myfile.js"></script>

<script>

$(document).ready(function(){

    $("div").hellotext(22);

});

</script>

</head>

<body>

<div> </ div>

</body>

</html>

Notice the jQuery code is the same, but now we display the greeting in a div container. With the "this" statement, we made this plugin dynamic and compatible with any of your web pages.

You'll make custom functions and plugins when you need to perform the same task throughout your web pages. Plugins make it much easier and faster to code web applications with common functionality. You can also find several plugins available on jQuery's official site, so you can download and integrate functionality without writing a single line of code.