Thursday, June 28, 2012

How to write your own functions in JQuery

This post is also part of learning jquery. When I was new to learn Jquery, I was facing lot of problems in creating my own functions in JQuery. Because I want to create one function at one place and use it everywhere by calling directly JqueryObject.function(). After got some experience then I started writing my own Jquery functions and using them in my projects.

Syntax of how we can create a new function is as below.
jQuery.fn.myownfunction = function() {
var currentObject = $(this) ; //currentObject holds the current object.
};

Example function for centering an element is shown below.

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / $(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / $(window).scrollLeft() + "px");
return this;
}

How to call it?
$("#popupDiv").center();

No comments:

Post a Comment