JQuery

is a well known JavaScript framework. Comes with pretty plugins, easy to learn, reduces amount of code and more on. JQuery Plugins reduces development time but what if you can not fine plugin that fulfill your need? Plugins helps you if you need to write snippet in multiple pages. Just add plugin JS file to your html and initialize it.

How to Create JQuery plugin - Sgeek

How its cool if you create your own plugin and use it in your development!! Writing your own plugin is not so hard that we think. Here, we will learn how to create simple plugin and bit more options and perform some tasks using out custom plugin.

Setup plugin

We will start with simple plugin. First of all, we need to create js file for plugin. Create a blank file and save it as jquery.myFirstPlugin.js. Include it to out html file in end of html file and off course include jquery-1.11.min.js (download) as its JQuery plugin.

<script type="text/javascript" src="js/jquery-1.11.min.js"></script>
<script type="text/javascript" src="js/jquery.myFirstPlugin.js"></script>

Default structure

 

Here, Include everything in (function($){}) self-enclosed pattern as we don’t want any confliction with other Javascript snippet on the page. $.fn allows you to define function as we gave myFirstPlugin name to our plugin. We will do magic inside function.

Creating simple plugin

Let’s start do something with our plugin. return will let you do something after call to plugin by returning call from isolated environment of plugin. Suppose we want to change text of div having class cls-title. $(this) is our target element which text we want to change.

Now, Its time to initialize plugin using below code. cls-title is div whose content we want to change.

That’s it, we’ve written our first jQuery plugin!

Passing arguments

Now, we will pass argument to our plugin.

Replace hard coded text with variable. Now we can pass any value to our plugin. Here is example

Setting default value

What if no text passed in initialization? Obviously we need to set default settings in our plugin.

Here, we have added default object called params and set default values of options using extend function. Hence, If we pass blank argument then it will set default values instead otherwise it will set.

$('.cls-title').myFirstPlugin({ text : 'Argument Title' });

Comment if you have any queries regarding JQuery plugin implementation.

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">