2 Jun 2020

Building first jQuery plugin

For those are jQuery lover, it is very handy to create their own plugin and use same code in different projects. I have written this plugin only for basic learning purpose and might be useful who want to create new plugin in jQuery. Don’t get mad if you find my plugin not much attractive. 😀
My plugin hiliteme simply highlight the matched text. It simply changes background color, text color and make bolder.
So lets start. I am assuming that you have already got fresh copy of jQuery and kept in correct path as in your page. If not you can simply download it from jQuery.com.

To make plugin flexible and more customizable we want to provide the mechanism to provide user for customization. But we also should not force user to input every parameters every time, so there must be some default values. jQuery is generous in this and provides extend method. Now lets add some parameters and default values. Updating our plugin.

(function($) {
// plugin definition
$.fn.hiliteme = function(params) {
defaults={   bcolor: 'green'  };
// merge default and user parameters
params = $.extend( defaults, params);
// for all selected node
return this.each(function() { 
// main work here
}); 
};
})(jQuery);

Here we have taken green background colour as default. If any other is provided then it will over-ride the default value.
Now its time to write for highlighting. We are changing css properties like font-weight, text color and background color.
Finally our plugin seems like this.

(function($) {
// plugin definition
$.fn.hiliteme = function(params) {
defaults={   bcolor: 'green'  };
// merge default and user parameters
params = $.extend( defaults, params);
// for all selected node
return this.each(function() {
// main work here
var $t = $(this);
$t.css("font-weight",700);
$t.css("background-color",params.bcolor);
$t.css("color",'white');
});
};})(jQuery);

Result:

Hope you found this useful.Thanks!

Nilambar

PHP Programmer, WordPress and Laravel Developer, Freelancer and a Blogger.

View all posts by Nilambar →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.