Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find coordinates of an HTML button or image, cross browser?

There was a thread on this in comp.lang.javascript recently where victory was announced but no code was posted:

On an HTML page how do you find the lower left corner coordinates of an element (image or button, say) reliably across browsers and page styles? The method advocated in "Ajax in Action" (copy I have) doesn't seem to work in IE under some circumstances. To make the problem easier, let's assume we can set the global document style to be "traditional" or "transitional" or whatever.

Please provide code or a pointer to code please (a complete function that works on all browsers) -- don't just say "that's easy" and blather about what traversing the DOM -- if I want to read that kind of thing I'll go back to comp.lang.javascript. Please scold me if this is a repeat and point me to the solution -- I did try to find it.

like image 317
Aaron Watters Avatar asked May 06 '09 12:05

Aaron Watters


2 Answers

In my experience, the only sure-fire way to get stuff like this to work is using JQuery (don't be afraid, it's just an external script file you have to include). Then you can use a statement like

$('#element').position()

or

$('#element').offset()

to get the current coordinates, which works excellently across any and all browsers I've encountered so far.

like image 189
Udo Avatar answered Nov 02 '22 21:11

Udo


I found this Solution from the web... This Totally Solved my Problem. Please check this link for the origin. http://www.quirksmode.org/js/findpos.html

/** This script finds the real position, 
 * so if you resize the page and run the script again, 
 * it points to the correct new position of the element.
 */
function findPos(obj){
   var curleft = 0;
   var curtop = 0;

   if (obj.offsetParent) {
      do {
         curleft += obj.offsetLeft;
         curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);

      return {X:curleft,Y:curtop};
   }
}

Works Perfectly in Firefox, IE8, Opera (Hope in others too) Thanks to those who share their knowledge... Regards,

ADynaMic

like image 29
Dilhan Maduranga Avatar answered Nov 02 '22 19:11

Dilhan Maduranga