0

How to get the co-ordinates of an element after onclick event ? I need to place an overlay just below an icon that was clicked.

Is there any such built in function provided by Javascript rather than manually writing a function for that ?

Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294
  • 2
    It's an area that can be more complex than it seems. I'd recommend the use of a good library to save you time and trouble, whether it's [jQuery](http://jquery.com), [Prototype](http://prototypejs.org), [YUI](http://developer.yahoo.com/yui/), [Closure](http://code.google.com/closure/library), or [any of several others](http://en.wikipedia.org/wiki/List_of_JavaScript_libraries). They'll also do a lot of *other* things to smooth over browser differences, provide utility functionality, and let you concentrate on what you're actually trying to build. – T.J. Crowder Jul 03 '11 at 07:40
  • 1
    To answer the direct question: no, there's no such built in function. You have to use the `event` object at some event handler to extract the position of the element. – Shadow The GPT Wizard Jul 03 '11 at 07:54
  • 1
    @T.J. As per the question history, OP is using PrimeFaces, which ships with jQuery and YUI. – BalusC Jul 03 '11 at 08:37

2 Answers2

0

In YUI, I use the getXY() function that returns the absolute page position of any object in the DOM. The source for that function in YUI2 is here: http://developer.yahoo.com/yui/docs/Dom.js.html.

In jQuery, it looks like you would use the .offset() method of a jQuery object: http://api.jquery.com/offset/.

You can either use one of those or look at their implementation and see how they work to code your own.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Try this one:

function getGlobalPos(el) {
  var p = {x:0,y:0};
  while (el) {
    p.x += el.offsetLeft;
    p.y += el.offsetTop;
    el = el.offsetParent;
  }
  return p;
}
ChipFind
  • 318
  • 2
  • 6