Creating custom JQuery plugin
Introduction
The jQuery library is designed to speed up JavaScript development. It helps you write less code by simplifying the way you write JavaScript. When using the jQuery library, you might find that you rewrite the same code for common functions. If this is the case, this may be a reason for you to write your own custom jQuery plug-in.
Prerequisites
This article assumes you have a basic understanding of JavaScript, jQuery,html.you can see complete code below
Getting Started
Step 1 : Define your plugin name. For eg : myplugin
$.fn.myplugin = function() {
return this.each(function() {
//Write your logic here.
});
};
jQuery
keyword is applied to the wrapper function, which lets you use the dollar sign within the plug-in as you do when using the fn
property. With the wrapper function in place, you can use the dollar sign in lieu of the jQuery
keyword anywhere throughout the plug-in without interfering with other third-party plug-ins.
Step 3 : Build your logic :
For eg- I click any child element for a element they will be hiden. We find all child and bind a custom function “hideElement” function on click event.
(function($) {
$.fn.myplugin = function() {
return this.each(function() {
var ele = $(this).children();
ele.click(hideElement);
});
function hideElement() {
$(this).hide();
return false;
}
}
})(jQuery);
Step 4 :use your plugin
$(document).ready(function() {
$("div#container").myplugin();
});