Print Shortlink

jQuery Plugin – I

jQuery is used in lot of projects these days, and one of the challenges is to write reusable, modularized code. jQuery Plugin is an approach to extending core jQuery API and creating reusable code. There a number of ways of creating a jQuery plugin. I want to discuss the easiest approach to developing a plugin in this post.

jQuery provides a property ‘fn’ in the core jQuery or $ class(!#$%). You can attach your own function to the “fn” property.

Let’s say you have a header with id as ‘info’ and you want to display the current date by writing
You can attach a date function in the core jQuery API like below:

$ = function(){
   $(this).text(new Date()+””);

Pretty simple!!! Isn’t? Let’s try another one.

Say, you want to change the text color of an element by having your own function changeColor.

$.fn.changeColor = function(color){

Huh!!!Even better.

Usually plugins are created in a JS file jquery-xxx.js. But to keep things simple, I have used the code inline. The complete code is given below.
<!DOCTYPE html>

<script src=”jquery-1.6.1.js”></script>
$.fn.changeColor = function(color){
$ = function(){
$(this).text(new Date()+””);
<h2 id=”welcome”>jQuery Plugin</h2>
<h5 id=”info”></h5>

We will discuss few more points of plugin in the subsequent posts. Have fun!!!

Leave a Reply