How to Create a Custom jQuery Plugin

jQuery is a powerful library which makes writing JavaScript code much easier. One of its main features is the possibility of extending default functionality with custom plugins. In this article, you will learn how to create your own jQuery plugin.

Basic Plugin Structure

A simple plugin is created by using the following code:

$.fn.helloWorld = function() {        // Plugin code goes here       // In this case, it sets the text of the element(s) to Hello World        this.each( function() {            $(this).text("Hello World!");        });}

The plugin name in this example is helloWorld. You can change it to whatever you want. Also, a plugin can be run on multiple DOM elements, so we’ve used the each() function, which loops trough those DOM elements.

Now, we need to make plugin variables and functions available only inside the plugin by creating a closure:

(function($) {}(jQuery)); 

When the plugin content is added, the code looks like this:

(function($) {   // This variable is available only inside this plugin   var text = "Hello World";    $.fn.helloWorld = function() {        this.each( function() {            $(this).text(text);        });    }}(jQuery)); 

The closure is used for protecting the $ alias. Since many JavaScript libraries use $ sign, a conflict could arise between libraries, which could break your plugin. Also, the closure enables us to have private functions and variables.

If you would like to use this plugin, you would write:

$("h2").helloWorld();

A plugin can also have one or more parameters:

 (function($) {    $.fn.helloWorld = function(my_text) {        this.each( function() {            $(this).text(my_text);        });    }}(jQuery)); 

The plugin would be used like this:

$("h2").helloWorld("My text goes here."); 

jQuery plugins can also have private functions, which are available only inside the plugin. Here is a simple example with the private function that handles debugging:

 (function($) {    $.fn.helloWorld = function(my_text) {       debug(this);        return this.each( function() {            $(this).text(my_text);        });    }    // Private function for debugging.    function debug( obj ) {        if ( window.console && window.console.log ) {            window.console.log("The following text was added:" + my_text);        }    };}(jQuery)); 

It is a good practice to save the plugin as a separate file and minify it (the plugin file name would be helloWorld.min.js). It is also great if you keep the version that is not minified when distributing the plugin package.

Plugin Options

A jQuery plugin can be customized by accepting options. The idea is to have default option values and to override only those that the plugin user has changed. This is done by passing the options as a plugin parameter and then calling the $.extend function:

 (function($) {   // This variable is available only inside this plugin   var text = "Hello World";    $.fn.helloWorld = function(options) {        // Plugin options default values        var settings = $.extend({            color: "red",            backgroundColor: "white"        }, options );        return this.each( function() {            $(this).text(text);            $(this).css("color", settings.color);            $(this).css("background", settings.backgroundColor);        });    }}(jQuery)); 

The plugin options are now in place. If we call the plugin without the options:

$("h2").helloWorld();

The default option values would be used. In this case, the text color would be red and the background would be white. However, if we call the plugin and specify the options:

$("h2").helloWorld({   color: "black"});

The default option value for color would be overridden by the custom value, so the text color would be black.

Customizability

Your custom jQuery plugin should be as customizable as possible. There are a few things to implement in order to achieve that. If your plugin creates DOM elements, then you should have a possibility to add an id or a class to those elements. For example:

(function($) {   // This variable is available only inside this plugin   var text = "Hello World";    $.fn.helloWorld = function(options) {        // Plugin options default values        var settings = $.extend({            class: "active",            id: "hello_world_container"        }, options );        return this.each( function() {            $(this).text(text);            $(this).attr("class", settings.class);            $(this).attr("id", settings.id);        });    }}(jQuery)); 

This way you could easily change the way the plugin looks.

It is also important to make the plugin support callback functions. Callback function is a function that is usually called after an event occurred. Callback functions are passed as plugin options:

(function($) {   // This variable is available only inside this plugin   var text = "Hello World";    $.fn.helloWorld = function(options) {        // Plugin options default values        var settings = $.extend({            class: "active",            id: "hello_world_container",            onTextAdd: function() {} // Callback function is empty by default        }, options );        return this.each( function() {            $(this).text(text);            $(this).attr("class", settings.class);            $(this).attr("id", settings.id);             // The text has been added            // Callback function is called at this point            settings.onTextAdd.call();        });    }}(jQuery)); 

Now, we will define a callback function and call the plugin:

$("h2").helloWorld({   onTextAdd: function() {      alert("The text has been added.");   }});

Next Steps

There are a lot of jQuery plugins available online now. Before starting to create your own plugin, check whether a plugin with the same functionality already exists by visiting the jQuery plugin registry or searching for it on Google.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

6 Tips for Setting Up a Decentralized Exchange

6 Tips for Setting Up a Decentralized Exchange

There’s no doubt that cryptocurrency is a complex and divisive topic in the modern financial landscape. There are those who are convinced that it’s nothing more than a bubble, but both who are well-informed are able to see the ways in which cryptocurrency can help them both build their fortune

user experience with someone on their phone

5 Ways to Improve Your Customers’ User Experience

They say you can’t judge a book by its cover, but just because they say that doesn’t mean it’s true. Consider how often you choose one sort of product over another just because it appeals to you. Then think about how often you’ve stopped using something because, simply put, it

How to Manage Your Finances after Buying a Home

How to Manage Your Finances after Buying a Home

Buying a home is a milestone in the journey of life – it’s one way to invest your money and create lasting memories. Now you know everything about a home purchase, home mortgage, and what is a conventional 97 loan but do you know what’s next after you sign the

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues.

The Fundamentals of Windows Logging

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues. Without it, tech experts might find it difficult to track a computer’s

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns Interstitial ads are full-screen advertisements that appear to grasp the attention of on-site prospects, creating opportunities for brands seeking effective ways to communicate their proposition of value. With such an attention-grabbing format and high-impact visuals, it’s no wonder why interstitial advertising is proving