jQuery is awesome. It is a fast, ligth-weight, cross-browser and feature-rich JavaScript library. It’s easy to learn and add interactivity to your website. It also comes with plenty of plugins to do almost whatever you need it to do.

It’s very boring and time consuming when we can’t find right plguin to suit our needs. But we can’t compromise with project code and functionality with native javascript. The simple solution might be to develop your jQuery plugin to meet your exact requirement.

Writing Your Own jQuery Plugins

Developing your own jQuery plugin isn’t as hard as it might seem at first. In this tutorial we will go through the process of developing a simple plugin, adding some options, and even perform a callback.

How jQuery Works

Before we write our own plugins, we must first understand a little about how jQuery works. Take a look at this code:

$( "a" ).css( "color", "red" );

This is some basic jQuery code, but do you know what’s happening behind the scenes? Whenever you use the $ function to select elements, it returns a jQuery object. This object contains all of the methods you’ve been using (.css(), .click(), etc.) and all of the elements that fit your selector. The jQuery object gets these methods from the $.fn object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well.

Start Your First jQuery Plugin

Here we will start our tutorial with a simple “Hello” plugin. First we will create our plugin file named as “jquery.hello.js” that will be keep in “js” dierectory of website. We also have jQuery libraray file in “js” directory of website.

Hello/
Hello/css
Hello/images/
Hello/js/jquery-1.11.1.min.js
Hello/js/jquery.hello.js
Hello/hello.html

We’ll also need to link our plugin file as well as jQuery code file into our HTML file. So we’ll place the following two lines at the bottom of HTML document, just before the closing tag:

<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.hello.js"></script>

Getting Started

Here we will start with the very basic shell of a traditional jQuery plugin. As jQuery comes with all the necessary hooks to build your plugin file easily But we still want to be mindful of good JavaScript practices.


(function($) {
$.fn.hello = function() {

}
}(jQuery));

The $.fn is jQuery’s way of allowing you to define your plugin, which we’ve named hello.

Let’s understand what’s going on. By including everything in the (function() {}) self-enclosed JavaScript pattern, we’re making sure that all the variables in our plugin will stay safely outside of the global namespace. We don’t want to cause any collisions with any other JavaScript used on the page, after all.

The other thing you will notice is that we’re defining our plugin as if jQuery was in it’s “no-conflict” mode. Again, we’re seeking to avoid colliding with other JavaScript on the page, and thus we want to make sure that our plugin isn’t reliant on the default $, which could be used by another library.

Now Do Something with Your Plugin

Now we ‘re going to do something for our plugin, but it’s still very simple for our demonstration purpose. That’s change all the text for the elements with the text "Hello, Web Revisions jQuery Plugin!".


(function($) {
$.fn.hello = function() {
this.each( function() {
$(this).text("Hello, Web Revisions jQuery Plugin!");
});
}
}(jQuery));

Actually when we’re invoking the plugin by attaching it to a jQuery selector, the object we’re acting upon is already a jQuery object, so we don’t need to wrap it in the $(this) structure you’re used to. However, once we start looping through each instance of the matching selector, we use the $(this) structure as we would any time we ran our selectors through .$.each().

For example we wanted to change the text of all of our <h2> headers on the following page:

jquery plugin hello

 

We will call the plugin as you’re already familiar, like so:

$(document).ready( function() {
$('h2').hello();
});

Results to :

juqery plugin results

 

Here we’re not quite done yet. As our plugin technically works, it’s living in its own little isolated world. That is, if you try and chain another jQuery action onto it, nothing’s going to happen because our plugin has led to a dead end. To fix this, be sure to return the results of the plugin as it loops through the DOM elements:


(function($) {
$.fn.hello = function() {
return this.each( function() {
$(this).text("Hello, Web Revisions jQuery Plugin!");
});
}
}(jQuery));

…congratulations! You’ve just written you’re first jQuery plugin!

Do More with Your Plugin

Now we have develop our jQuery plugin but when cleint ask that text to be translated into French, then what to do now. Well, we could start by just adding an argument. Let’s take our plugin above, and instead of hard-coding the text into the plugin, we can replace it with a variable and pass that along when we invoke the plugin.

(function($) {
$.fn.hello = function( customText ) {
return this.each( function() {
$(this).text( customText );
});
}
}(jQuery));

There, now we can pass any text we’d like to our plugin. Now we will pass French translation that we need, which we now use as the parameter of our plugin:

<script>
$(document).ready( function() {
$('h2').hello('Bonjour, Web révisions jQuery Plugin');
});
</ script>

Now our web page looks like this:

jquery plugin french

Handle Custom Options and Callback

Now we have a plugin in which we have passed text but what if no text was passed when we called the plugin? As it’s written, the plugin would simply blank out the text of our matched elements, and we probably don’t want that. Also if we want to add variables to add custom values. Definetly we need to add options to plugin to work in the long term.

As we know that we need the specific text to be customizable. Now if we want the text color and font style be customizable. So here we will add options object to our plugin, along with some default values using the $.extend method:.


(function($) {
$.fn.hello = function( options ) {
// Default settings
var settings = $.extend({
text : 'Hello, Web Revisions jQuery Plugin!',
color : null,
fontStyle : null
}, options);
return this.each( function() {
});
}
}(jQuery));

Now we have a settings object that, when the plugin is called deprived of any parameters , will use what we’ve established as the default text. We also have two other properties of our settings object, “color” and “fontStyle”, that have no default beyond null. For this plugin, we don’t need to establish any color or font style beyond what is laid out in our CSS, but they’re there for the overriding if we want. We just have to make use of them:


return this.each( function() {
$(this).text( settings.text );

if ( settings.color ) {
$(this).css( 'color', settings.color );
}

if ( settings.fontStyle ) {
$(this).css( 'font-style', settings.fontStyle );
}
});

 

As the main purpose of this plugin is to replace text, it makes sense to always replace the text with whatever is provided, which is why it also makes sense to provide a default value so that something appears if the plugin is called without any options. But the color and font style options are tested for and only acted upon if they are provided.

Suppose if we want to translate the text into Spanish, and and beyond that they want the text to be blue and italic. Fortunately, our plugin can now handle all these requests:


$('h2').hello({
text : 'Hola , Revisiones Web jQuery Plugin !',
color : '#005dff',
fontStyle : 'italic'
});

jquery plugin spanish

Now if we want to display an alert to display a complete task message. For this, we will handle callbacks. Callbacks are options to JavaScript functions that are themselves JavaScript functions. They’re also not unique to jQuery but it’s very simple.

We need is to establish one more variable in our options object:


var settings = $.extend({
text : 'Hello, Web Revisions jQuery Plugin!',
color : null,
fontStyle : null,
status : null
}, options);

Now we have a “status” variable to perform an action when our plugin completes its action. We will call this with jQuery $.isFunction:


return this.each( function() {
if ( $.isFunction( settings.status ) ) {
settings.status.call( this );
}
});

On the HTML page side, our code becomes:

$('h2').hello({
text : 'Hola , Revisiones Web jQuery Plugin!',
color : '#005dff',
fontStyle : 'italic',
status : function() { alert( 'Done Successfully!' ) }
});

 

jquery plugin done

 

Really custom jQuery plugins are a right option when you have not found plugin in jQuery plugin repository to suite your requirement and you have to do a lot of the same things over and over in your JavaScript. By writing your own jQuery plugin, you can avoid doing same things again and again and also save your precious time.

email

Leave a Reply

Your email address will not be published. Required fields are marked *

Web Design Quote | Web Design Estimate
Categories

Related Post

Archives
July 2017
S M T W T F S
« May    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
Pond Calculator

Select Pond Shape

Powered by Pond Supplies for Less

Our Calculator Estimates The Following Size For Your Pond Liner:

Pond Volume: 0 US Gallons | Liters: 0 | Imperial Gallons: 0

Estimated Pond Liner Size: 0 X 0 Feet

Note: Pond liner size estimate includes a 1 foot overlap on all sides.

Powered by Pond Supplies For Less