How to create jQuery Plugin?
When you are working with JavaScript code using jQuery library, you might come across where you need to make a piece of logic/functionality available throughout your UI code. For instance, you have method, and you want to make available of that method on jQuery object. In such case, you may need to build a jQuery Plugin .
In this article you will learn how to create jQuery plugin, use/integrate in application, and test the plugin results.
Before we start building the jQuery plugin, let’s first understand a little bit how jQuery exactly works on below line of code:
[pre class="brush:javascript; toolbar: false;" title=""] $("span").attr("type", "card"); [/pre]
When you use the$ function on any html element, it creates and return a jQuery object. This jQuery object has the access to rest of all jQuery function like attr(), prop(), css(), click(), etc. All these methods are actually came from $.fn object. This $.fn object contains all the jQuery object methods. If we need to write our own method and use it, then $.fn should contain our method as well.
Create jQuery Plugin
We will create one sample plugin and see what the steps are involved in it. Let’s define our plugin requirement.
Assume that we need to create plugin that takes the text of any HTML element and transform such a way that first letter of each word in the text is become as capital letter.
As we discussed above plugin method should be attached to$.fn object. Let’s create a plugin method called capitalizeFirstLetter() to $.fn as shown below in a JavaScript file capitalizeFirstLetter.js
[pre class="brush:javascript; toolbar: false;" title=""] $.fn.capitalizeFirstLetter = function() { //take original text of the element var originalText = this.text(); //split original text with space var splitText = originalText.split(' '); //change first character of every word to upper case for(var i = 0; i<splitText.length; i++) { splitText[i] = splitText[i].charAt(0).toUpperCase() + splitText[i].substring(1); } //reconstruct all the words as string again var modifiedText = splitText.join(' '); //replace the original text with modified text this.text(modifiedText); } [/pre]
With the above code our jQuery Plugin called capitalizeFirstLetter is created, and we’ll see how to consume the same now.
Consume jQuery Plugin
Before start using our capitalizeFirstLetter plugin, let’s build a sample HTML as below:
[pre class="brush:html; toolbar: false;" title=""] <body> <span>this text is going to capitalize the first letter of each word using custom jQuery plugin!</span> <p>build your own jquery plugin now!!</p> </body> [/pre]
Then referrer the jQuery library and capitalizeFirstLetter.js files to your project. And, call the capitalizeFirstLetter() method on above HTML span and paragraph tags.
You can see that the text of span and paragraph elements are changed such a way that it’s first letter of each word become as capital letter.
Pass Parameters to jQuery Plugin
You might need most of the times passing parameters to plugin to change the behavior of it as and when value of parameter change.
Let’s say in out above example we need to change the text color as user wishes, in such case let’s extend the plugin function to access the parameters as show below:
[pre class="brush:javascript; toolbar: false;" title=""] (function($) { $.fn.capitalizeFirstLetter = function(options) { //parameters needed for plugin, default color of text is green var settings = $.extend({ color: 'green' }, options); //take original text of the element var originalText = this.text(); //split original text with space var splitText = originalText.split(' '); //change first character of every word to upper case for(var i = 0; i<splitText.length; i++) { splitText[i] = splitText[i].charAt(0).toUpperCase() + splitText[i].substring(1); } //reconstruct all the words as string again var modifiedText = splitText.join(' '); //replace the original text with modified text this.text(modifiedText); //change the color of the text to blue this.css('color', settings.color); } }(jQuery)); [/pre]
Note: You might noticed from above code that$.fn object is inside the Invoked function. This is to protect the $ symbol. In general, $ is the alias of jQuery function, hence you are using the $ everywhere instead of jQuery function when you write code. What if third party JavaScript libraries like Knockout, Backbone, etc., use the same $ sign? If multiple frameworks are using the same $ sign, then one of them might stop working. In such cases you need to release the $ alias using jQuery.noConflict() statement. To make your plug-in work with other plugins, you might need to add your code inside the Invoked function as shown above.
While consuming the plugin, let’s pass the color name parameter as you wish to plugin.
[pre class="brush:javascript; toolbar: false;" title=""] //call plug in method $('span').capitalizeFirstLetter({color:'blue'}); $('p').capitalizeFirstLetter(); [/pre]
When you run your code, now you will see the text of the color changed.
That is all for now, and hope you have understood the fundamentals of building, consuming, and testing a jQuery custom plugin. If you have any further questions, please throw them in below comments box.
In this article you will learn how to create jQuery plugin, use/integrate in application, and test the plugin results.
Before we start building the jQuery plugin, let’s first understand a little bit how jQuery exactly works on below line of code:
[pre class="brush:javascript; toolbar: false;" title=""] $("span").attr("type", "card"); [/pre]
When you use the
Create jQuery Plugin
We will create one sample plugin and see what the steps are involved in it. Let’s define our plugin requirement.
Assume that we need to create plugin that takes the text of any HTML element and transform such a way that first letter of each word in the text is become as capital letter.
As we discussed above plugin method should be attached to
[pre class="brush:javascript; toolbar: false;" title=""] $.fn.capitalizeFirstLetter = function() { //take original text of the element var originalText = this.text(); //split original text with space var splitText = originalText.split(' '); //change first character of every word to upper case for(var i = 0; i<splitText.length; i++) { splitText[i] = splitText[i].charAt(0).toUpperCase() + splitText[i].substring(1); } //reconstruct all the words as string again var modifiedText = splitText.join(' '); //replace the original text with modified text this.text(modifiedText); } [/pre]
With the above code our jQuery Plugin called capitalizeFirstLetter is created, and we’ll see how to consume the same now.
Consume jQuery Plugin
Before start using our capitalizeFirstLetter plugin, let’s build a sample HTML as below:
[pre class="brush:html; toolbar: false;" title=""] <body> <span>this text is going to capitalize the first letter of each word using custom jQuery plugin!</span> <p>build your own jquery plugin now!!</p> </body> [/pre]
Then referrer the jQuery library and capitalizeFirstLetter.js files to your project. And, call the capitalizeFirstLetter() method on above HTML span and paragraph tags.
[pre class="brush:javascript; toolbar: false;" title=""]
<script type="text/javascript" src="CapitalizeFirstLetter.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//call plug in method
$('span').capitalizeFirstLetter();
$('p').capitalizeFirstLetter();
});
</script>
[/pre]
With the above code you have consumed the jQuery plugin in your code. Now let’s start test and see how the results look like.
Test jQuery Plugin
Access your page/file (Ex: Index.html) where you have above codes in web browser.
With the above code you have consumed the jQuery plugin in your code. Now let’s start test and see how the results look like.
Test jQuery Plugin
Access your page/file (Ex: Index.html) where you have above codes in web browser.
You can see that the text of span and paragraph elements are changed such a way that it’s first letter of each word become as capital letter.
Pass Parameters to jQuery Plugin
You might need most of the times passing parameters to plugin to change the behavior of it as and when value of parameter change.
Let’s say in out above example we need to change the text color as user wishes, in such case let’s extend the plugin function to access the parameters as show below:
[pre class="brush:javascript; toolbar: false;" title=""] (function($) { $.fn.capitalizeFirstLetter = function(options) { //parameters needed for plugin, default color of text is green var settings = $.extend({ color: 'green' }, options); //take original text of the element var originalText = this.text(); //split original text with space var splitText = originalText.split(' '); //change first character of every word to upper case for(var i = 0; i<splitText.length; i++) { splitText[i] = splitText[i].charAt(0).toUpperCase() + splitText[i].substring(1); } //reconstruct all the words as string again var modifiedText = splitText.join(' '); //replace the original text with modified text this.text(modifiedText); //change the color of the text to blue this.css('color', settings.color); } }(jQuery)); [/pre]
Note: You might noticed from above code that
While consuming the plugin, let’s pass the color name parameter as you wish to plugin.
[pre class="brush:javascript; toolbar: false;" title=""] //call plug in method $('span').capitalizeFirstLetter({color:'blue'}); $('p').capitalizeFirstLetter(); [/pre]
When you run your code, now you will see the text of the color changed.
That is all for now, and hope you have understood the fundamentals of building, consuming, and testing a jQuery custom plugin. If you have any further questions, please throw them in below comments box.
No comments: