Tuesday, December 20, 2011

JQuery Find Absolute Position of element

Scenario: Get coordinates of a element(X, Y) to display overlay message immediate next or immediate below the element.
Based on the coordinates set the absolute position of the control (overlay) to display it accordingly. The overlay can be started any side/corner of the element.

Get the element object using JQuery:
var obj = $('[id$=controlelement]');
Get the position of the element from Left
function findPosLeft(obj) 
{
var pos = obj.offset();
var left = pos.left;
return left;
}
Get the position of the element from Top
function findPosTop(obj) 
{
var pos = obj.offset();
var top = pos.top;
return top;
}
Get the position of the element from Bottom
function findPosBottom(obj) 
{
var pos = obj.offset();
var top = pos.top;
var height = obj.height();
var bottom = top + height;
return bottom;
}
Get the position of the element from Right
function findPosRight(obj) 
{
var pos = obj.offset();
var left = pos.left;
var width = obj.width();
var right = left + width;
return right;
}

3 comments:

  1. Better i would use for finding top position is

    "return obj.offset().top;"

    And also i dont think it should be a method we can directly use object.offset().top;

    ReplyDelete
  2. Kranthi,
    Well, it can be used directly as you said. However functions are always Reusable & Scalable and also a best practice for operations.

    ReplyDelete
  3. Well written post.It help to create an axis.It help my professional many times.Please create more blogs related.Thanks for it.

    Ecommerce developer

    ReplyDelete