JavaScript Find Position

I’ve been trying to use the findPosX() & findPosY() functions from Peter-Paul Koch’s excellent ‘quirksmode‘ site. The purpose of these functions is to find the absolute X and Y co-ordinates of an HTML element. They work well in both Internet Explorer and Firefox, but the results can be pretty rubbish on Safari.

I’ve made a small adjustment that fixes this problem. I’ve moved the loop exit from the start of the loop to the middle. Safari was failing to add in the offset of the outermost containing element. Here’s the modified code:

  function findPosX(obj)
    var curleft = 0;
          curleft += obj.offsetLeft;
          obj = obj.offsetParent;
    else if(obj.x)
        curleft += obj.x;
    return curleft;

  function findPosY(obj)
    var curtop = 0;
          curtop += obj.offsetTop;
          obj = obj.offsetParent;
    else if(obj.y)
        curtop += obj.y;
    return curtop;


You are free to use this script for any purpose.

Peter-Paul Koch has implicitly dedicated his original version of this script to the public domain [link]. I hereby dedicate my version of the script to the public domain.

If you wish to give us credit, I suggest you just say: by Peter-Paul Koch & Alex Tingle. A link would be nice, too.

Comment · Comments Feed · TrackBack

  1. Dave said,

    1 August, 2005 @ 15:25

    Thanks man! this was confusing the hell out of me!

  2. Craig said,

    2 August, 2005 @ 23:15

    Outstanding work! thank you!

  3. Jared said,

    19 August, 2005 @ 20:34

    Hi, I had been trying to use your code on my web site but I still face some problem. I have a couple of questions hope you can help… Thank you.

    I wish to find a X,y or Left,Top position of an image within a web page, can I do that using your script? I had tried using DIV encapsulation on the but I still cannot read out the XY coordinate. Do you have any alternative solution?

    Thank you very much. Regars

  4. alex said,

    19 August, 2005 @ 21:09

    Jared: What? These functions find the X,Y position of an object. Why would you need an alternative solution?

    If it doesn’t work for you, then you’ll need to be more specific. How about an example and an indication of which browser you’re using.

  5. Matt said,

    10 October, 2005 @ 16:18

    Hi Jared, I’ve tried these scripts from your site and quirksmode but always get a 0 returned whereever i position the element.

    I’m just using IE6 on XP sp2

    i just have an img tag that i’ve put in various positions, then call you functions always get 0, any ideas?

  6. alex said,

    10 October, 2005 @ 16:29

    Matt: (who’s Jared? I’m Alex :-)) Can you point me to an example that fails?

  7. selva said,

    25 November, 2005 @ 11:42

    hi, sir i’m using IE 6. i need to get the position of a table. Functions findPosX, findPosY are not working. It returns 0.

    could you help me sir?

    with rgrds, Selva

  8. alex said,

    25 November, 2005 @ 15:19

    selva: Give me a link to an example, and I’ll tell you what I think.

  9. buckwheat said,

    2 December, 2005 @ 06:00

    Killer script – just what I was looking for! Is it ok to use it? who to give credit or linkt to

  10. André said,

    7 February, 2006 @ 17:03

    Valew, cara… me ajudou bastante!!!

  11. Jai said,

    10 February, 2006 @ 10:32

    Neat script :-) thanks muchly for this effort.

  12. Kalvin said,

    22 February, 2006 @ 23:29

    Awesome. I was trying to use Koch’s version with both IE and Netscape and it was causing issues. You version works well. Thanks.

  13. Wender said,

    14 March, 2006 @ 21:14

    Wow!!!!!!!!!! Thank you a lot!!!!!

  14. tom callahan said,

    24 March, 2006 @ 16:46

    Thanks for the fix, solves the same problem in Opera by the way. Here’s a version formatted a little more strictly as far as including the “{” for the if/else statements in case anyone else had a problem with the formatting of the version on this page.

    function findPosX(obj) {
        var curleft = 0;
        if (obj.offsetParent) {
            while (1) {
                if (!obj.offsetParent) {
        } else if (obj.x) {
        return curleft;
    function findPosY(obj) {
        var curtop = 0;
        if (obj.offsetParent) {
            while (1) {
                if (!obj.offsetParent) {
        } else if (obj.y) {
        return curtop;
  15. alex said,

    24 March, 2006 @ 22:37

    Hi Thomas,

    I’m an old hand, so I’m able to view your fervent rejection of my
    coding style with a wry humour. In years gone by, I would have been
    offended by your waste of characters and illogical brace-placement. :-P

    When I get a minute, I’ll clean up your version and post it for any
    other K+R luddites who may happen across my page.

    Happy hacking, and I hope that you see the light one day.

  16. Emery Wooten said,

    13 April, 2006 @ 05:59

    Jarad and others. I too was getting nothing but 0 returned from the function call. I was calling the function from a script inside a table cell and not from an event like onMouseover.

    If that is your problem, place your calling script OUTSIDE of the table and it will work properly. The function itself should be in the head of your page.

  17. Elan said,

    24 April, 2006 @ 05:51

    Good Work, Thanks a lot…!

  18. neo_1883 said,

    24 April, 2006 @ 06:21

    Thankyou for the code it is really use full……we can use it in many ways to make animations using javascript…

  19. mike said,

    25 April, 2006 @ 22:53

    This really helped me out, Thanks!!!

  20. Hawk said,

    9 May, 2006 @ 15:20

    Programmers scare me with how fanatical they get over their code style. Here is the same code written in compressed format with reverse indent.

    The newbie coder will most likely have their eyes bug out of their sockets just looking at it. If you are an old hand, reverse indenting can be a life saver when its added to scripts of 1,000+ lines. It allows you to see more of the code in one viewing without it scrolling off the page. Although it does scroll to right some, most of the scrolling is controlled.

    function findPosX(obj){
    var curleft = 0;
    if (obj.offsetParent){
    if (!obj.offsetParent){break}
                         }else if(obj.x){curleft+=obj.x}
    return curleft;
    function findPosY(obj){
    var curtop = 0;
    if (obj.offsetParent){
    if (!obj.offsetParent){break}
                        }else if(obj.y){curtop+=obj.y}
    return curtop;
  21. Adam Hamilton said,

    25 May, 2006 @ 16:19

    Emery Wooten is right – the script only works in IE when called from an event (onload doesn’t seem to count). I had the same problem as everyone else, with a zero or -1 return, but this has fixed it. Thanks Alex and Emery!

  22. Pradyot said,

    3 June, 2006 @ 16:06

    Thanks, most helpful.

  23. Hubbers said,

    12 June, 2006 @ 15:12

    Super code using it to solve problem of full screen floating pages that sometime float under one another on small screen resolutions.

        if (objx.offsetParent) {
            while (1) {
                curleft += objx.offsetLeft;
                if (!objx.offsetParent) {
                    objx = objx.offsetParent;
            } else if (objx.x) {
                curleft += objx.x;
                return curleft;
            curleft = curleft - 250;
            document.getElementById('folder').style.width = '250px';
            document.getElementById('rightcenter').style.width = curleft;
  24. Ebi said,

    20 June, 2006 @ 17:39

    Great script !!!

    Very useful !

  25. Dean said,

    28 June, 2006 @ 16:33

    Alex, Sorry to bug you but I’m getting 0 for X and Y value when using FireFox.

    Here’s some snippets:



    function getMouseXY(e) 
        var isNS4 = (document.layers) ? true : false;
        var isIE4 = (document.all && !document.getElementById) ? true : false;
        var isIE5 = (document.all && document.getElementById) ? true : false;
        var isNS6 = (!document.all && document.getElementById) ? true : false;
        var isNS = (isNS4||isNS6) ? true : false;
        var isIE = (isIE4||isIE5) ? true : false;
        if (isIE)
            alert('findPosX:' + findPosX(e));
            alert('findPosY:' + findPosY(e));
        else if (isNS)
            alert('findPosX - NS:' + findPosX(e));
            alert('findPosY - NS:' + findPosY(e));

    Any help would be appreciated.


  26. Bill said,

    29 June, 2006 @ 00:07


    Great script and very helpful. I am also try to get the postion (coordinates) of the right/bottom point of an object. It seems offsetRight and offsetBottom are not valid.

    Do you know this to be the case or am I clueless here? Thanks again for you excellent remake of Peter-Paul’s script.

  27. Steve said,

    10 July, 2006 @ 16:51

    You totally just saved me from spending a few hours wondering how to do something just like this. Now I can spend that time eating ice cream!

  28. EA said,

    17 July, 2006 @ 13:39

    More oo and shortened;

    function Point(x, y) {
        this.x = x;
        this.y = y;
    function getObjCoords(o) {
        var oX = 0;
        var oY = 0;
        if (o.offsetParent) {
            while (1) {
                    if (!o.offsetParent) {
        } else if (o.x) {
        //alert(oX + ":" + oY);
        return new Point(oX, oY);
  29. Praeses said,

    27 July, 2006 @ 21:59

    Ran across this by accident searching for something else, but here’s the function I typically use, not sure how compatible it is but I find it a bit cleaner.

    function getPos(inputElement) {
        var coords =  new Object();
        coords.x = 0;
        coords.y = 0;
        try {
            targetElement = inputElement;
            if(targetElement.x && targetElement.y) {
                coords.x = targetElement.x;
                coords.y = targetElement.y;
            } else {
                if(targetElement.offsetParent) {
                    coords.x += targetElement.offsetLeft;
                    coords.y += targetElement.offsetTop;
                    while(targetElement = targetElement.offsetParent) {
                        coords.x += targetElement.offsetLeft;
                        coords.y += targetElement.offsetTop;
                } else {
                    //alert("Could not find any reference for coordinate positioning.");
            return coords;
        } catch(error) {
            return coords;
  30. greanie said,

    8 August, 2006 @ 14:49

    Hi Alex,

    I’ve been using your script pretty much unchanged but it isn’t working in my application. I have a series of photos in a container, each wrapped by a div. The div’s are floated left so that the photos look like they are next to each other in a row and the photos wrap to the next line if there are more photos than can fit on a row. When I try to get the position of any image, I always get the coordinates for the top-left most image in the matrix, not the coordinates of the current image. Basically, the script is giving the position of the image where it would have put it if there wasn’t anything in the way already. Does the offsetLeft & offsetTop fail for floating containers? I’ve tried this on Firefox 1.0.7 & IE 6. Any help would be appreciated, otherwise and FYI to others.



  31. iduniq said,

    10 August, 2006 @ 07:03

    The code does not work in this instance.

    A  B

    function showloc(){
  32. iduniq said,

    10 August, 2006 @ 07:10

    Does not work in this instance.


    function showloc(){ alert(findPosX(document.getElementById('mydiv'))) }

  33. iduniq said,

    10 August, 2006 @ 07:14

    Does not work in this instance.

    A table with width is 60%, inside table is one cell td is align right. Inside td is a div, on click div position x of div returns only zero.

  34. iduniq said,

    10 August, 2006 @ 07:32

    Stupid me, found the error when i colored the div, div was actually stretched to position zero eventhough the display starts in the middle of the browser.

  35. Del said,

    12 August, 2006 @ 08:00

    Praeses, thank you for that code!

  36. Tom said,

    15 August, 2006 @ 12:51

    Tip from quirksmode site if you are trying to position an element using this script:

    “In ‘strict mode’ you must add ‘px’ to the value, or Mozilla, Explorer on Mac and Safari will refuse to place the layer anywhere.”


    document.getElementById( element2 ).style.left = findPosX( element1 ) + 'px';

    Great script by the way, thanks for the time saver.

  37. Nitin said,

    15 September, 2006 @ 09:16

    this is not mine just copied from a open source: what = object offsettype = “left” for x-pos and “top” for y-pos

    function getposOffset(what, offsettype) { var totaloffset=(offsettype==”left”)? what.offsetLeft : what.offsetTop; var parentEl=what.offsetParent; while (parentEl!=null) { totaloffset=(offsettype==”left”)? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop; parentEl=parentEl.offsetParent; } return totaloffset; }

  38. ericShinn said,

    21 September, 2006 @ 05:31

    How’s this for minimalistic?

    function getPos (obj) { var pos = {x: obj.offsetLeft||0, y: obj.offsetTop||0}; while(obj = obj.offsetParent) { pos.x += obj.offsetLeft||0; pos.y += obj.offsetTop||0; } return pos;


    … and you access the info by: alert(“X = “+getPos(myElement).x+” and Y = “+getPos(myElement).y);

    Cheers, eShinn

  39. Geeta said,

    25 September, 2006 @ 10:24

    Hi !

    I had a problem in identifying the position of an element inside a div which is scrolling. Is there a way to get the position of the element relative to the displayed area, rather than getting the fixed position always ?

    thanks in advance !

  40. Chris I said,

    13 October, 2006 @ 07:03

    Works a treat! Many thanks :)

  41. yoshi said,

    17 October, 2006 @ 14:16

    2 Geeta: For problem in identifying the position of an element inside a div which is scrolling Use prototype.js!!!

    download it from

    read documentation at – in the end of doc about “Position”

    use this function :

    GetBounds : function(element) { var iebody = (document.compatMode && document.compatMode != “BackCompat”)? document.documentElement : document.body;
    var dsocleft = document.all? this.iebody.scrollLeft : pageXOffset; var dsoctop = document.all? this.iebody.scrollTop : pageYOffset;

        var posReal = Position.realOffset(element);
        var pos = Position.cumulativeOffset(element);
        var top =  pos[1] - posReal[1] + dsoctop;
        var left = pos[0] + posReal[1] - dsocleft;
        var offsetWidth = element.offsetWidth;
        var offsetHeight = element.offsetHeight;
        return {left: left, top: top, width: offsetWidth, height:  offsetHeight};

    adapt this function to your needs. i’m note sure it has no errors.

  42. Kalle said,

    22 October, 2006 @ 11:57

    If you need to find the position in Internet Explorer you have to use a timer function, otherwhise Explorer returns “-1″. I think this is because Explorer needs to draw the entire webpage before it can return the position of an element. (In Firefox this is not necessary.) Maybe you can also use “window on load” in IE.

    function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { curleft = obj.offsetLeft; curtop = obj.offsetTop; while (obj = obj.offsetParent) { curleft += obj.offsetLeft; curtop += obj.offsetTop; } }

    return [curleft,curtop];


    function UpdateTimer() { if(timerID) clearTimeout(timerID);

    var position = findPos(document.getElementById("name"));


    setTimeout(“UpdateTimer()”, 1000);

  43. dale said,

    23 October, 2006 @ 18:40

    I’ve been playing around with your script and quirksmode’s script, but like others, I’ve been getting a return of x = 0, y = 0. I tried adding the “px” afterwards to no avail. does it have something to do with the doctype? I’ve tried strict and transitional doctypes for xhtml 1.0 but still nothing. any clue as to what is happening? What’s really strange is that in IE6 and FF, when i put: if (!obj.offsetParent) alert (“no offsetParent”) and it returns that alert.

    Any clues? thanks

  44. NooM said,

    20 November, 2006 @ 10:33

    I’ve got return 0 as well. My html page is generated by PHP,javascript and html itself. But in my test page I found that if your html open tag without closed tag. You will get 0 from findpos() function. Does anybody has another method in IE to find element pos?(like obj.x and obj.y in firefox).


  45. Sven said,

    22 November, 2006 @ 15:28

    I have also developed a solution for this problem, a little bit shorter but it works also fine:

        function getX(obj){
            return obj.offsetLeft + (obj.offsetParent ? getX(obj.offsetParent) : obj.x ? obj.x : 0);
        function getY(obj){
            return (obj.offsetParent ? obj.offsetTop + getY(obj.offsetParent) : obj.y ? obj.y : 0);
  46. Dr.Link said,

    27 November, 2006 @ 12:28

    Cool. woorks fine.

  47. Nideaderedes » Blog Archive » Buscar la posición de un objeto con Javascript said,

    7 December, 2006 @ 08:40

    […] He encontrado en un estupendo script que permite conocer la posición de cualquier objeto de una página html. […]

  48. Norberto said,

    11 December, 2006 @ 20:47

    Thank’s, man!!! your script is very useful for me.

  49. simon said,

    13 December, 2006 @ 08:54

    if some of the parent elements has defined border, than posX, which your function returns is not correct. It should be: posX=findPosX(obj)+allBorderWidths

    Do you have some function which includes also a borders?

  50. Larry said,

    21 December, 2006 @ 21:42

    I have been using this code….

    Anything wrong with this?? Seems a bit shorter if anything else….

    function getXpos(elem) { while (elem != null && !elem.offsetParent) elem = elem.parentNode; if (elem == null) return 0; return (elem.offsetLeft + getXpos(elem.parentNode)) }

    function getYpos(elem) { while (elem != null && !elem.offsetParent) elem = elem.parentNode; if (elem == null) return 0; return (elem.offsetTop + getYpos(elem.parentNode)) }

  51. Jacob said,

    6 January, 2007 @ 02:04

    Hey Guys…YOUR FUNCTION WAS TERRIFIC!!! was looking for a solution for my drag and drop function,

    solved all problems when i stumbled upon this script…THANKS DUDE!

  52. bachew said,

    16 January, 2007 @ 07:17

    Thanks for your code, just realize that should use node.offsetParent rather than node.parentNode. :) Anyway, here’s more compact function:

    function absoluteTop (node) { var top = 0; while (node.offsetParent) { top += node.offsetTop; node = node.offsetParent; } return top; };

  53. Nate said,

    19 January, 2007 @ 16:43

    I’m not sure what the difference between PPK’s and this new version is, because they both work the same for me.

    I’m having trouble finding position of relative elements in IE7, is this possible?

    any help would be appreciated.


  54. michele said,

    20 January, 2007 @ 21:37

    Hi, sorry I’m new in javascript, the script to retrieve information about X and Y sounds good but I need to have the opportunity to read the X and Y coords in my (that is dragable) and, if possible to have an “onclick” coords update at the end of one trip with my , can anybody help me?? thank you very much. and.. can I see the coords directly in an tag??

    thx again from Italy_England

  55. Tad said,

    21 January, 2007 @ 06:51

    Great function, VERY useful!

  56. Mumo said,

    22 January, 2007 @ 08:11

    How can i use this code, please give me an example of how to place where the functions are called…. Help!!!!!

  57. Greg said,

    22 January, 2007 @ 10:01

    Perfect! This saves me a lot of time working out how to do this. Thanks.

  58. Eugene Morozov said,

    24 January, 2007 @ 11:03

    Hello, Unfortunately this script doesn’t allow to find a position of the particular word on the page. It would only allow to find position of the outer text node. :(

    I wonder if there’s a way to find exact coordinates of any particular word on the page. Even if it would work only in Firefox. Eugene

  59. Snowdog said,

    15 February, 2007 @ 18:52

    Thanks for the script – thankfully this page was indexed on google! I just spent an hour trying to figure out how to get the absolute position of an object in JavaScript by myself.

    Thanks for the information!


  60. verbatim said,

    15 February, 2007 @ 21:58

    I’m having a problem with FF2.0.

    I’ve tried this script and others similar to it and related to it. I keep getting strange values for the Y offset. In stylesheets, I set everything to zero: body { padding:0px; margin:0px }. then placed one single image on a blank page with an href around it. using mouseover to show me the y offset, I keep getting different y offsets depending on the height of the image (manually changed for experimentation). The natural height of the image is 88, yet somehow the offset keeps saying 73.

    If I have set everything to zero: 1. shouldn’t the offset always be zero? 2. why does the y offset change every time I change the image height?

  61. Norm Sherman said,

    19 March, 2007 @ 17:29

    Depending on how you implemented this script: I recommend adding ‘obj=document.getElementById(obj);’ right above ‘var curleft = 0;’ and ‘var curtop = 0;’.

    Sans-Quote :)

    Firefox will always return ZERO if it’s not called via an event.

  62. Patrick said,

    21 March, 2007 @ 03:16

    Great work on the script… have been looking all around for such simple script to improve the dynamic gradient background script on Firefox 2.0!

    Thanks mate!

  63. Kyle White said,

    23 March, 2007 @ 20:33

    It seems that this function, and basically every other one I’ve seen on the net has the same problem, which I’ll try to explain here.

    When giving it an A (link element), when that is a container for an image, Mozilla gives very strange result, but it seems that it can be explained.

    In the case of giving an A object displayed as an inline element, with an image contained within, you get basically:

    (Real Y Offset) + (Image Height – Font Height).

    I assume that means Mozilla thinks the A’s position is really where the text would start if it were there.

    You can visualize this problem by putting a border around the A element.

    Setting the display CSS property to block corrects this.

    If you can’t switch to block mode, you can correct for this problem by simply giving the element for the image, and not the A.

  64. Satish Vellanki said,

    5 April, 2007 @ 20:45

    Thank you very much, I was in need of this

  65. Kunal Kadakia said,

    8 May, 2007 @ 10:22

    Hey, First of all, thanks a lot for posting the script. It does work with IE, Firefox & Safari. BUT there is one problem: When you rezise the window, the script looses its track of the absolute position of the element and the positioning is then done in a relative manner. e.g the position of the element is 400px from the top. If you scroll down by 100px, and then again refresh the page, the element will be positioned at 500px from the top instead of its absolute position which is 400px.

    Is there a way to get around with this resizing problem.

    Thanks Kunal

  66. venkatesh said,

    17 May, 2007 @ 14:48

    Hi i new to javascript, im using this function to find the Y-postion function findPosY (obj) {

    var curTop=0; if (obj.offsetParent){ while(obj.offsetParent) { curTop+=obj.offsetTop; obj=obj.offsetParent; } } else if (obj.y){ curTop+=obj.y; } alert(curTop); return curTop; }

    This is my html code


    It alert’s only 0.

    Could you help me what im wrong. Thanks in advance.

  67. David said,

    18 May, 2007 @ 01:06


    I’ve been using the following. It takes into account the scroll position of the window as well as any scrolling objects (css overflow: scroll|auto)

    function getPosition(elementId) {

    var element = document.getElementById(elementId);
    var left = 0;
    var top = 0;
    if (element != null)
        // Try because sometimes errors on offsetParent after DOM changes.
            while (element.offsetParent)
                // While we haven't got the top element in the DOM hierarchy
                // Add the offsetLeft
                left += element.offsetLeft;
                // If my parent scrolls, then subtract the left scroll position
                if (element.offsetParent.scrollLeft) {left -= element.offsetParent.scrollLeft; }
                // Add the offsetTop
                top += element.offsetTop;
                // If my parent scrolls, then subtract the top scroll position
                if (element.offsetParent.scrollTop) { top -= element.offsetParent.scrollTop; }
                // Grab
                element = element.offsetParent;
        catch (e)
            // Do nothing
        // Add the top element left offset and the windows left scroll and subtract the body's client left position.
        left += element.offsetLeft + document.body.scrollLeft - document.body.clientLeft;
        // Add the top element topoffset and the windows topscroll and subtract the body's client top position.
        top += element.offsetTop + document.body.scrollTop - document.body.clientTop;
    return {x:left, y:top};


    You would then use something like the following to use it:

    var pos = getPosition(‘IMAGEOS’); alert(‘x:’ + pos.x.toString() + ‘, y:’ + pos.y.toString());

    Note that your IMAGEOS object will not exist until the page is loaded. If you need it’s co-ordinates at load time, then wrap it in a function called by window.onload or it can be called from an event from another page object.

  68. aissi said,

    21 May, 2007 @ 13:21

    Hello and thanks for the script. I was also having issues with the functions returning only 0.

    I was running the function from onClick-event like this: findPosX(‘element_id’)

    Got it working by running it like this: findPosX(document.getElementById(‘element_id’))

  69. nitj said,

    25 May, 2007 @ 12:25

    no dude i’m not getting it… plz can u corerct my code….

    function window_open(val){ var newWindow; var urlstring = “common/calendar.jsp?requestSent=” +val; var urlstyle = ‘height=230,width=320,titlebar=0,toolbar=no,minimize=0,status=no,menubar=no,location=no,scrollbars=no,directories=no ‘;

        newWindow =,'Calendar',urlstyle);
    function getX(obj){
        return obj.offsetLeft + (obj.offsetParent ? getX(obj.offsetParent) : obj.x ? obj.x : 0);
    function getY(obj){
        return (obj.offsetParent ? obj.offsetTop + getY(obj.offsetParent) : obj.y ? obj.y : 0);
  70. AjayK said,

    18 June, 2007 @ 09:02


    I applied the position find method for following html file. But it gives me incorrect x and Y position if I apply .submenu style to tag. but returns me correct x and Y position if I dont apply any style to tag.

    Could anybody plz let me know why am I getting different values for same objects, and any solution to overcome it?

    .submenu { visibility:block; position: relative}

    document.onkeyDown = handleKeyDown; function handleKeyDown() { if(eGPSFindLinkObj()) { eleAnchorObj = eGPSFindLinkObj(); var eO = getPosition(eleAnchorObj); alert(‘Final calculated position: Left = ‘+eO.x +’ Top = ‘+eO.y); }


    function getPosition(elementObj) {

    //var element = document.getElementById(elementId); var element = elementObj; var left = 0; var top = 0;

    if (element != null) { // Try because sometimes errors on offsetParent after DOM changes. try { while (element.offsetParent) { // While we haven’t got the top element in the DOM hierarchy // Add the offsetLeft left += element.offsetLeft; // If my parent scrolls, then subtract the left scroll position if (element.offsetParent.scrollLeft) {left -= element.offsetParent.scrollLeft; }

            // Add the offsetTop
            top += element.offsetTop;
            // If my parent scrolls, then subtract the top scroll position
            if (element.offsetParent.scrollTop) { top -= element.offsetParent.scrollTop; }
            // Grab
            element = element.offsetParent;
    catch (e)
        // Do nothing
    // Add the top element left offset and the windows left scroll and subtract the body's client left position.
    left += element.offsetLeft + document.body.scrollLeft - document.body.clientLeft;
    // Add the top element topoffset and the windows topscroll and subtract the body's client top position.
    top += element.offsetTop + document.body.scrollTop - document.body.clientTop;

    } return {x:left, y:top}; }

    function eGPSFindLinkObj() { var eObj = null; var strStart = “event.srcElement”; var strMid = “”; var strEnd = “.tagName.toLowerCase()” var strTag = eval(strStart + strMid + strEnd);

    while(strTag != "a" && strTag != "html" && strTag != "area" && strTag != "img")
        strMid += ".parentElement";
        strTag = eval(strStart + strMid + strEnd);
    if(strTag == "a" || strTag == "area" || strTag == "img"){
        eObj = eval(strStart + strMid);
        return  eObj;
    else return ;


    Green Widgets Blue Widgets Red Widgets

    Click Left/right on any of above link

  71. AjayK said,

    18 June, 2007 @ 09:03

    By Tag I mean li tag.

  72. AjayK said,

    18 June, 2007 @ 09:08

    Oho it parsed my html file, the content of my html file are, I replaced ” with ‘]’, please read inplace []

    [html] [style type=text/css] .submenu { visibility:block; position: relative} [/style] [script language = “javascript” src=’cal.js’][/script] [body]

    [ul id=widgets] [li class=submenu ][a href=greenwidgets.html]Green Widgets[/a][/li] [li class=submenu ][a href=bluewidgets.html]Blue Widgets[/a][/li] [li class=submenu ][a href=redwidgets.html]Red Widgets[/a][/li] [/ul][BR] [BR] [h4] Click Left/right on any of above link [/h4]

    [/body] [/html]

  73. NykO18 said,

    25 June, 2007 @ 11:00

    Wonderful, it works pretty well, thanks !

  74. Abdel said,

    29 June, 2007 @ 08:14


    The problem isn’t in the Script from Alex. My be her (!!!

    Question: How can I use “” in FireFox?


    function findPosition(oElement) { var pos = getPosition(document.getElementById(oElement)); var posleft = parseInt(pos); //alert(posleft); var element = document.getElementById(‘ReightDiv’); = posleft + 170; }

    function getPosition(objx) {
    var curleft = 0;
       if (objx.offsetParent) {
        while (1) {
            curleft += objx.offsetLeft;
            if (!objx.offsetParent) {
                objx = objx.offsetParent;
        } else if (objx.x) {            
            curleft += objx.x;
            return curleft;
        return curleft;        
  75. vishal patil said,

    19 July, 2007 @ 12:51

    Really nice one. very helpful.

  76. my name said,

    21 July, 2007 @ 12:12

    thanks Alex, it really worked…

  77. maylow hayes said,

    2 August, 2007 @ 15:58

    thank you veeeeery much!

  78. 16 действительно полезных решений для JavaScript « шаманские бредни said,

    12 August, 2007 @ 14:01

    […] 8. Набор функций, позволяющих получить координаты элемента на экране пользователя. Если ваш документ статичен относительно окна и не имеет скроллбаров – лучше использовать функцию getPosition – так будет быстрее. Ð’ обратном случае используйте getAlignedPosition – она учитывает положения скроллбаров. Только обратите внимание: значение top у элемента может быть орицательным, если элемент верхней частью за пределами окна – для синхронизации с курсором мыши иногда нужно обнулить в этом случае высоту. Основной скрипт позаимствован из одного блога, Aligned-версия – результат поисков по сусекам и совмещения с информацией из двух статей (при обнаружении DOCTYPE IE входит в свой собственный, несколько непредсказуемый, режим). […]

  79. Dev said,

    22 August, 2007 @ 11:55

    Indeed a killer script!!! Good work Alex and God bless you Tom for correcting the formating issues.

  80. Vishnu said,

    24 August, 2007 @ 11:32

    This worked for me. Thank you.

  81. montoto said,

    3 October, 2007 @ 14:12

    If you need to get the position of an element that may be inside a div with scroll content, then you should decrement the scrollTop or scrollLeft values of the element. This is: function findPosX(obj) { var curleft = 0; if(obj.offsetParent) while(1) { curleft += obj.offsetLeft; curleft -+ obj.scrollLeft; if(!obj.offsetParent) break; obj = obj.offsetParent; } else if(obj.x) curleft += obj.x; return curleft; }

  82. Roshan said,

    12 October, 2007 @ 12:58

    Hey this is really nice, very well written. I tried to search a lot for standard property to get x & y position, but didn’t get that. But this really helped me a lot. I appreciate a lot your work.

    Take care and congratulation. Roshan

  83. Raja said,

    26 October, 2007 @ 14:25

    Thanks for your coding

  84. Infosgs said,

    3 November, 2007 @ 15:22


    I’m using your script a lot and it goes but…

    Yesterday i’ve tried to find position of DIV element that was created after page load (Ajax environment), the problem is that this DIV have its origin (x=0 , y=0 , position=absolute) not to the window left-top corner, but at left-top corner of its parent that i call AjaxContainer.

    So, find position function retrieve DIV position into AjaxContainer how maximum parent.

    My scenario is BODY -> ELEMENTS -> AJAXCONTAINER (about in middle of page) -> DIV.

    Anyone can help me?

  85. shiva said,

    15 November, 2007 @ 06:35

    thanks for this coding, first its not working in mozila forefox n safari after adding the px its working fine,

    thanks for all :)

    Tom said, 15 August, 2006 @ 12:51

    Tip from quirksmode site if you are trying to position an element using this script:

    “In ’strict mode’ you must add ‘px’ to the value, or Mozilla, Explorer on Mac and Safari will refuse to place the layer anywhere.”


    document.getElementById( element2 ).style.left = findPosX( element1 ) + ‘px';Great script by the way, thanks for the time saver.

  86. Chris said,

    19 November, 2007 @ 19:56

    Nope, this code fails for elements in relatively positioned parents, like tables. Nice try though.

  87. Eyal said,

    21 November, 2007 @ 14:05


    Tanks for the script.

    What about page with scroll , that causes the obj to dynamically change it’s position?


  88. shanti said,

    29 September, 2008 @ 12:15

    very nice script…..

  89. David Underhill said,

    4 December, 2008 @ 03:44

    Great code — thanks for sharing!

  90. Elven Lee said,

    29 December, 2008 @ 07:58

    Thanks for share…

  91. Gabriel said,

    1 January, 2009 @ 23:54

    I dont know if this is a problem due to the script or something else on my project. But when i use this script it works 100% perfect on FF and abit wrong on IE:

    Im using a div centered both horizontally and vertically with the help of a table. On my onmouseover-event i trigger a function that’ll take the x- and y-pos of its div with the help of this script. After that I take these x and y coordinates and put them in yet another div (my little div-popup which is supposed to position itself directly above the div that triggered the onmouseover-event). The thing is, when i change the size of the browser-window my popup-div position itself on different Y-coordinates. The X-coordinates are the same but vertically the popupdiv changes location whenever i resize the browserwindow.

    Any fix for this? :)

  92. Khaled Ayad said,

    12 January, 2009 @ 15:36

    Thank you Alex !

    The code works 100% on both IE and FireFox. The function written by you at the first beginning of this page (July 2005) are correct and don’t need any modification, at least for IE & FireFox. I think all the wrong returns other people had were due to error in calling the functions.

  93. Corrado said,

    15 January, 2009 @ 10:52

    Cool script. It works like a charm!

    Tested with: – FF – Chrome 1.0.154 – IE 7.0


  94. Richard said,

    5 February, 2009 @ 06:30

    thanks for that. I expected jquery to have this functionality built in but no luck.

  95. jeff said,

    13 February, 2009 @ 03:57

    Excellent ! Now…. going further. Can you recommend the best method of finding the elements width and height based on this script? Any help would be great.

    Thanks again!

  96. nagesh said,

    17 February, 2009 @ 15:45

    That was very useful, thanks alot.

  97. Kefler said,

    25 February, 2009 @ 16:14

    The scripts above will not work for all elements. Elements which are absolute positioned and elements which are relatively positioned on the page will return different values. Relative positioned objects will return the x and y relative to the parent, and thus why the loop through the parent nodes, however, absolute positioned elements will return a value relative to the HTML object of the page but still have the same parent in which they are appended to.

    Also, elements which do not have CSS/javascript assigned position attributes will only be caught with offsetTop and offsetLeft. A mixture of no pre-defined x and y, predefined x, y and absolute x and y will really screw up most scripts. The reason for the -1 values is because the scripts do not exit when they hit the HTML and/or Body objects which are at -1 and 0 respectively.

    The solution to the problems above is to limit the parent nodes in which it calculates the offset top from. Absolute positioned objects should NOT run through a parent check as since they are absolutely positioned, their position is already ABSOLUTE and thus the script should end there and return their position. relative positioned objects and objects which have no top and left assigned to them via css should then be checked against their parent nodes but only certain parent node types.

    Div > Table > TR > TD > TH

    So, say you have an image inside a TH tag, the relative position of the TH tag is important as cellspacing and cellpadding play a huge roll in the positioning of that image within the TH tag. Next the offset parent to the TH tag will be the TR tag which also has to be taken into consideration for the same reasons as stated for the TH tag. Then you’ll hit table which also has to be accounted for and then you’ll either hit some other layout object like a parent table or div, or td, etc.

    In short, x and y position accumulation should only happen for layout objects, divs, tables, spans, and anything else that can be a container for other html elements. positions of the html and body elements should NOT be checked as they are -1 and 0 respectively.

  98. Michael said,

    27 February, 2009 @ 15:52

    Thanks so much for this. I hate re-inventing the wheel…

  99. Harsh said,

    7 March, 2009 @ 01:15

    Does not work for Div obj. I did pass object and it passes me 945 number all the time.

    I dont know whts wrong?

  100. Tar said,

    12 March, 2009 @ 18:12

    One more variant of the routine. I found it more convenient to have just one function instead of two which returns a single object pos. The x and y attrs may be accessed using pos.x and pos.y

    Modifications: – merging two functions findPosX and findPosY into one function FindPos – returning a single value ‘pos’ – getting rid of the ‘break’ statement from within the ‘while’ loop

    Whould it still work under the browsers other than IE?

    function FindPos(ctrl) { var pos = {x:0, y:0};

    if (ctrl.offsetParent)
            pos.x += ctrl.offsetLeft;
            pos.y += ctrl.offsetTop;
            ctrl = ctrl.offsetParent;
    else if (ctrl.x && ctrl.y)
        pos.x += ctrl.x;
        pos.y += ctrl.y;
    return pos;


  101. hindusthan said,

    23 March, 2009 @ 08:52

    how to fix float menu this not show in header,but when header ends show in full left include

  102. vijay said,

    8 April, 2009 @ 07:19

    Thanks …………… did my day

  103. Cocoh said,

    24 April, 2009 @ 15:49

    Thanks so much! This baby rocks! :)

  104. Dan Garland said,

    2 May, 2009 @ 16:31

    This worked first time for me in on xubuntu/linux firefox 3… many thanks Dan

  105. Aurelio said,

    15 July, 2009 @ 10:25

    This was unbelievably useful! :D

    Many thanks!!


  106. dave.dolan said,

    27 July, 2009 @ 18:37

    This works most of the time in as many browsers as I have found, but if you nest the element inside a table, inside a div, inside a table, inside a table, inside a table, inside a div, it doesn’t work in FireFox and Chrome, and returns 0 for x and y. The way I know is because I use it in a SharePoint web part that has a customized master page that was done with a table layout. Yuk, and I still haven’t found a way to get it to work now. For some crazy reason, it actually does work in IE still. That’s not the way things usually go!

  107. Haresh Karkar said,

    7 October, 2009 @ 09:51

    Thank man. It is very useful.

  108. Paul said,

    23 October, 2009 @ 21:35

    I’m writing an iPhone app and need to automatically position keywords found in a long web page. Your function seems to be exactly what I need. The problem is that I have zero knowledge of javascript. What do I substitute for the argument obj? I tried a few things like: keyword; the regular expression, /keyword/i; and search(keyword). Nothing worked. Any suggestions as to what to do? Thanks

  109. rampraveen83 said,

    1 February, 2010 @ 03:16

    thank u so much

  110. Gayan said,

    4 February, 2010 @ 07:12

    Thanks very much.. it’s work perfectly…

  111. Xavi said,

    12 March, 2010 @ 13:10

    Out of curiosity, what elements have x and y properties on them?

    In other words when does if(obj.x) equal true?

  112. pardailhan said,

    2 April, 2010 @ 08:12

    bonjour à tous. Désolé mais ce code ne fonctionne pas dans tous les cas (cell d’une table en scolling dans un div overflow auto ). Utiliser la fonction de prototype.js ou un dérivé…

  113. Eli said,

    23 May, 2010 @ 09:50

    Thx :)

  114. HungTD7 said,

    31 May, 2010 @ 14:08

    Thanks a lot. It is so helful

  115. nary said,

    8 June, 2010 @ 12:10

    hai sir, am selecting my treeview node in my web page, when i select that node, it will show one div on the top right of the page with some details.

    but i need to get that div at the currect position of my tree node where i selected that node.

    this is my problem.

    plz help.

    thanks in advance.

  116. dexdix said,

    5 July, 2010 @ 12:23

    Does not work on IE 8, Mozila 6, Opera . It jus not work :D I realy need this function.

  117. Guy Schalnat said,

    3 August, 2010 @ 15:00

    Even more oo (object oriented) and even shorter (and with the curly braces correctly placed for maintainability and readability, not to fit as much code as possible on a 24×80 terminal screen, which is why we used to put them to the far right):

    function Size(x, y, w, h)
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    function getSize(n)
        var s = new Size(n.offsetLeft, n.offsetTop, n.offsetWidth, n.offsetHeight);
        while (n.offsetParent && n.offsetParent.offsetLeft !== undefined)
            n = n.offsetParent;
            s.x += n.offsetLeft;
            s.y += n.offsetTop;
        return s;
    var s = getSize(p);
    alert("x = " + s.x + ", y = " + s.y + ", w = " + s.w + ", h = " + s.h);
  118. Mehdi said,

    16 August, 2010 @ 08:02

    awesome script. Made my day :)

  119. Sunny Boy said,

    18 September, 2010 @ 07:07

    Problem Description: i have a table in the html, each row of the table have hidden division for overlay.Table columns contains [+] buttons. When i click on [+] button i have to show the hidden overlay at [+] button.i mean absolute left and absolute top of overlay should start at [+] button Can some one help me…

  120. Paresh said,

    27 September, 2010 @ 15:45

    Thanks. You saved my day.

  121. Rafael said,

    7 October, 2010 @ 18:16

    Unbelievable, it works!!! Thanks a lot!!!

  122. dphir said,

    15 November, 2010 @ 06:28

    hai sir,why the value of x and y position always 0 i want to get selected text from web page.. i have been tried to add obj with this obj = document.getSelection(); but it doesn’t work. can you help me and give me an advice.. thank you

  123. Mahesh said,

    18 February, 2011 @ 10:50

    Sorry, But It not works in IE7+

  124. Bob Toovey said,

    23 February, 2011 @ 21:45

    Great script, thanks very much. Spent weeks trying to get positions from images etc – nearly bald now because of it! So I am very happy that I came across your solution. Cheers!

  125. Flo said,

    21 March, 2011 @ 18:48


    thanks @Guy Schalnat & @Peter-Paul Koch & Alex Tingle. Nothing else worked for my relative positioned divs.

    @Guy Schalnat script works like a charm!

    Greetz, Flo

  126. Morgan said,

    22 June, 2011 @ 05:15

    Very nice, script. However I found that it didn’t work if there object was nested in other objects, multiple ones of which were absolutely positioned. After no small amount of heartache, I added a counter to the loop, starting with 0 and incremented in the loop. I then added the following if clause in the beginning of the “do” loop (note this is IE-centric, but could easily be generalized):

    if (obj.currentStyle.position == ‘absolute’ && counter > 0) break;

    I initially tried to add the additional restriction in the “while” constraint so I wouldn’t have to use a counter, but I kept getting javascript errors when I did that. Anyway, it seems to help in this situation.

  127. Vinod Sharm said,

    7 July, 2011 @ 01:28

    Thanks a lot!! It really works!! Saved my day.

  128. tu said,

    27 September, 2011 @ 06:26

    Thank you, I did apply your script to zoom picture script

  129. john said,

    30 September, 2011 @ 06:04

    it was working for me now it is just returning “0”. does anyone know whats wong?

  130. Saeed Alkhalil said,

    25 October, 2011 @ 07:17

    Thanks a lot, it works well

  131. smartphone guy said,

    7 March, 2012 @ 14:07

    Thanks for the explanation and code man!

  132. bhawesh said,

    29 April, 2012 @ 04:00

    Hi, can you help me out that i want to access a position of image on page but their is more than one then and they are generated dynamically so if i give id them then all have same id so how i can difference between that what img is mouseover i wanna to get xy position of img on which mouse over is done

    can you please reply ASAP


  133. Paul D said,

    6 May, 2012 @ 15:57

    Cheers Works fine. Must have visited goodness knows how many web sites with rubbish solutions, before finding this.

  134. Paul D said,

    20 May, 2012 @ 14:02

    Update, almost works fine, but…

    It doesn’t take into account the possibility that the browser window is reduced in size so that scroll bars appear. Then when the window is scrolled, the coordinates are offset and incorrect, which messes up mouse detection etc. It’s a problem in all browsers from what I can see.

    But I see someone in the comments has pointed out the issue of scrollbars etc.

Leave a Comment