Step by Step to Create jQuery Plugin

Some of people make the library using a jQuery plugin only by download. Because many people think that a task is too complex that they just ignore doing it. That’s been my mindset when thinking about developing a plugin for jQuery. By keeping the core library as small as possible – about 16 kb – users can then apply additional plugins at their own discretion. Today, I will tell you step by step to create a jQuery plugin start from “Center” plugin from scratch.

Let’s get started! Before develop a plugin, you might ask yourself why you should want to do it. The first and best reason is it’s ability to maintain chainability, because the best feature of jQuery is the chainability. It allows you to do things like:

$('.className').addClass('enabled').append('<a href="#">Click here</a>').click( func );
This would take every element with a class name of ‘className’, add a new class name to it, append some HTML, and set a click event handler. When you develop a plugin, you have the ability to inject your own functionality while still maintaining the chain. We want to create a plugin that will dynamically adjust the styling of a specified element in order to keep it vertically and horizontally centered on the page at all times – even when the browser window is resized. Very little is required up front.

jquery plugin

Step 1- Create jQuery Plugin

Download jQuery-1.2.6.pack.js  in here

Step 2- Create jQuery Plugin

Start from creating a plugin is to create a blank Javascript file. Naming conventions state that the file should be named “YourPluginName.jQuery.js”. When you created this file, make sure that you create a reference to it in your document.

<head>
    <script src="jquery-1.2.6.pack.js" type="text/javascript">
    <script src="center.jQuery.js" type="text/javascript">
</head>

Step 3 – Create jQuery Plugin

Paste this code in the following code.

(function($){  
 
$.fn.center = function(){  
 
var element = this;  
 
$(element).load(function(){  
 
changeCss();  
 
$(window).bind("resize", function(){
    changeCss();
});  
 
function changeCss(){  
 
    var imageHeight = $(element).height();
    var imageWidth = $(element).width();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();  
 
    $(element).css({
        "position" : "absolute",
        "left" : windowWidth / 2 - imageWidth / 2,
        "top" : windowHeight /2 - imageHeight / 2
    });
};
});  
 
};  
 
})(jQuery);
Everytime you create a plugin, it must be wrapped with:
$.fn.center = function(){};
“Center” should be replaced with whatever your plugin’s name is. This lets jQuery know that you’re extending its methods. Now, though it does absolutely nothing, we can call our center method with:
$(function(){
  $("#someElement").center();
});

Step 4 – Create jQuery Plugin

You must understand how to manually center an image on a page before creating the plugin. First, your element must be positioned absolutely. Otherwise, it obviously won’t budge when we alter the “left” and “top” values. Next, the image needs to be shifted 50% of the browser’s width to the left. Finally, in order to compensate for the image’s width, we need to subtract one half of the image’s width.

function changeCss(){
      var imageHeight = $(element).height();
      var imageWidth = $(element).width();
      var windowWidth = $(window).width();
      var windowHeight = $(window).height();  
 
      $(element).css({
          "position" : "absolute",
          "left" : windowWidth / 2 - imageWidth / 2,
          "top" : windowHeight /2 - imageHeight / 2
      });
 };

Step5 -Create jQuery Plugin

The last step, create a listener for when the browser window is resized.

$(window).bind("resize", function(){
      changeCss();
  });
“ChangeCss()” is a function that adjusts the left and top values of our image. By calling it again when the window is resized, jQuery will recalulate those values. HTML Full Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Plugin Tutorial</title>
    <script src="jquery-1.2.6.pack.js" type="text/javascript"></script>
    <script src="center.jQuery.js" type="text/javascript"></script>
 
    <script type="text/javascript">
    $(function(){
        $('img').center();
    });
    </script>
</head>
<body>
<div>
    <img src="nettuts.png" alt="Nettuts" />
</div>
</body>
</html>
JavaScript Full Code
(function($){
 
$.fn.center = function(){
 
var element = this;
 
$(element).load(function(){
 
changeCss();
 
$(window).bind("resize", function(){
    changeCss();
});
 
function changeCss(){
 
    var imageHeight = $(element).height();
    var imageWidth = $(element).width();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
 
    $(element).css({
        "position" : "absolute",
        "left" : windowWidth / 2 - imageWidth / 2,
        "top" : windowHeight /2 - imageHeight / 2
    });
};
});
 
};
 
})(jQuery);

[demo href="http://demo2.denbagus.net"]

this is step by step how to create jQuery plugin

HP0-S30 and MB6-283 questions provide you 100% exam pass guarantee. You can get access to testking MB3-462 & MB5-198 exams with multiple prep resources of MB3-465.

EmailFacebook0Google+0StumbleUpon72Twitter45Reddit0Pinterest0Digg

3 Responses to “Step by Step to Create jQuery Plugin”

  1. http://sig.kz
    Возможны различные варианты услуг ведения бухгалтерского учета:
    - постановка бухгалтерского и налогового учета с «нуля»;
    - комплексное бухгалтерское сопровождение;
    - услуги по составлению разовой бухгалтерской и налоговой отчетности;

  2. Great! As for the demo though, when I go to it in Firefox on Mac, the image is placed top left. If I refresh, then it appears in the centre.
    Bit of a bug?

    I know the tut wasn’t about this particular plugin as such, but thought I’d mention it.
    Andy

Trackbacks/Pingbacks

  1. 54 jQuery Tutorials and How Tos - 4 November 2011

    [...] 022. Step by Step to Create jQuery Plugin [...]

Leave a Reply