473,385 Members | 1,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to get the object's position(top,left) when the css style has position:relative?

I study http://www.javascripttoolbox.com/lib...tion/index.php source and its doesn't work fine for the following code: (I hope both IE and firefox are working well)

Expand|Select|Wrap|Line Numbers
  1.  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
  3. "http://www.w3.org/TR/REC-html40/strict.dtd">
  4. <html>
  5. <head>
  6. <title>Test</title>
  7. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  8. <script type="text/javascript">
  9. /**
  10.  * Copyright (c)2005-2009 Matt Kruse (javascripttoolbox.com)
  11.  * 
  12.  * Dual licensed under the MIT and GPL licenses. 
  13.  * This basically means you can use this code however you want for
  14.  * free, but don't claim to have written it yourself!
  15.  * Donations always accepted: http://www.JavascriptToolbox.com/donate/
  16.  * 
  17.  * Please do not link to the .js files on javascripttoolbox.com from
  18.  * your site. Copy the files locally to your server instead.
  19.  * 
  20.  */
  21.  
  22. var Position = (function() {
  23.   // Resolve a string identifier to an object
  24.   // ========================================
  25.   function resolveObject(s) {
  26.     if (document.getElementById && document.getElementById(s)!=null) {
  27.       return document.getElementById(s);
  28.     }
  29.     else if (document.all && document.all[s]!=null) {
  30.       return document.all[s];
  31.     }
  32.     else if (document.anchors && document.anchors.length && document.anchors.length>0 && document.anchors[0].x) {
  33.       for (var i=0; i<document.anchors.length; i++) {
  34.         if (document.anchors[i].name==s) { 
  35.           return document.anchors[i]
  36.         }
  37.       }
  38.     }
  39.   }
  40.  
  41.   var pos = {};
  42.   pos.$VERSION = 1.0;
  43.  
  44.   // Set the position of an object
  45.   // =============================
  46.   pos.set = function(o,left,top) {
  47.     if (typeof(o)=="string") {
  48.       o = resolveObject(o);
  49.     }
  50.     if (o==null || !o.style) {
  51.       return false;
  52.     }
  53.  
  54.     // If the second parameter is an object, it is assumed to be the result of getPosition()
  55.     if (typeof(left)=="object") {
  56.       var pos = left;
  57.       left = pos.left;
  58.       top = pos.top;
  59.     }
  60.  
  61.     o.style.left = left + "px";
  62.     o.style.top = top + "px";
  63.     return true;
  64.   };
  65.  
  66.   // Retrieve the position and size of an object
  67.   // ===========================================
  68.   pos.get = function(o) {
  69.     var fixBrowserQuirks = true;
  70.       // If a string is passed in instead of an object ref, resolve it
  71.     if (typeof(o)=="string") {
  72.       o = resolveObject(o);
  73.     }
  74.  
  75.     if (o==null) {
  76.       return null;
  77.     }
  78.  
  79.     var left = 0;
  80.     var top = 0;
  81.     var width = 0;
  82.     var height = 0;
  83.     var parentNode = null;
  84.     var offsetParent = null;
  85.  
  86.  
  87.     offsetParent = o.offsetParent;
  88.     var originalObject = o;
  89.     var el = o; // "el" will be nodes as we walk up, "o" will be saved for offsetParent references
  90.     while (el.parentNode!=null) {
  91.       el = el.parentNode;
  92.       if (el.offsetParent==null) {
  93.       }
  94.       else {
  95.         var considerScroll = true;
  96.         /*
  97.         In Opera, if parentNode of the first object is scrollable, then offsetLeft/offsetTop already 
  98.         take its scroll position into account. If elements further up the chain are scrollable, their 
  99.         scroll offsets still need to be added in. And for some reason, TR nodes have a scrolltop value
  100.         which must be ignored.
  101.         */
  102.         if (fixBrowserQuirks && window.opera) {
  103.           if (el==originalObject.parentNode || el.nodeName=="TR") {
  104.             considerScroll = false;
  105.           }
  106.         }
  107.         if (considerScroll) {
  108.           if (el.scrollTop && el.scrollTop>0) {
  109.             top -= el.scrollTop;
  110.           }
  111.           if (el.scrollLeft && el.scrollLeft>0) {
  112.             left -= el.scrollLeft;
  113.           }
  114.         }
  115.       }
  116.       // If this node is also the offsetParent, add on the offsets and reset to the new offsetParent
  117.       if (el == offsetParent) {
  118.         left += o.offsetLeft;
  119.         if (el.clientLeft && el.nodeName!="TABLE") { 
  120.           left += el.clientLeft;
  121.         }
  122.         top += o.offsetTop;
  123.         if (el.clientTop && el.nodeName!="TABLE") {
  124.           top += el.clientTop;
  125.         }
  126.         o = el;
  127.         if (o.offsetParent==null) {
  128.           if (o.offsetLeft) {
  129.             left += o.offsetLeft;
  130.           }
  131.           if (o.offsetTop) {
  132.             top += o.offsetTop;
  133.           }
  134.         }
  135.         offsetParent = o.offsetParent;
  136.       }
  137.     }
  138.  
  139.  
  140.     if (originalObject.offsetWidth) {
  141.       width = originalObject.offsetWidth;
  142.     }
  143.     if (originalObject.offsetHeight) {
  144.       height = originalObject.offsetHeight;
  145.     }
  146.  
  147.     return {'left':left, 'top':top, 'width':width, 'height':height
  148.         };
  149.   };
  150.  
  151.   // Retrieve the position of an object's center point
  152.   // =================================================
  153.   pos.getCenter = function(o) {
  154.     var c = this.get(o);
  155.     if (c==null) { return null; }
  156.     c.left = c.left + (c.width/2);
  157.     c.top = c.top + (c.height/2);
  158.     return c;
  159.   };
  160.  
  161.   return pos;
  162. })();
  163.  
  164.  
  165. </script>
  166. <style>
  167. #idText { border:1px red solid ; }
  168.  
  169. #mainDiv {
  170.     position:relative ;
  171.     margin: 100px 0 0 50px;
  172.     border: 1px solid blue;
  173.     padding: 20px;
  174. }
  175. .marker {
  176.     position:absolute;
  177.     width:10px;
  178.     height:10px;
  179.     border:1px solid black;
  180. }
  181.  
  182. #marker1 {
  183.     background-color:yellow;
  184. }
  185. #marker2 {
  186.     background-color:blue;
  187. }
  188. #marker3 {
  189.     background-color: #00FF00;
  190. }
  191. </style>
  192. <body>
  193. <div id="marker1" class="marker"></div>
  194. <div id="marker2" class="marker"></div>
  195. <div id="marker3" class="marker"></div>
  196.  
  197. <div id="mainDiv">
  198.     ########<div id="idText">a text</div>############
  199.     <br />
  200.     <table cellpadding="1" cellspacing="1" border="1"><tr>
  201.         <td onClick="getEditorPosition(this);">&nbsp;&nbsp;Cell1&nbsp;&nbsp;</td>
  202.         <td onClick="getEditorPosition(this);" >&nbsp;&nbsp;Cell2&nbsp&nbsp;</td>
  203.     </tr></table>
  204. </div>
  205. <script type="text/javascript">
  206.  
  207. var pos=Position.get(document.getElementById('mainDiv' ));
  208. Position.set(document.getElementById('marker1'),pos);
  209.  
  210. var pos=Position.get(document.getElementById('idText'));
  211. Position.set(document.getElementById('marker2'),pos);
  212.  
  213.  
  214. function getEditorPosition(cell) {
  215.     var pos=Position.get(cell);
  216.     Position.set(document.getElementById('marker3'),pos);
  217. }
  218.  
  219.  
  220. </script>
  221. </body>
  222. </html>
  223.  
  224.  
  225.  
Thanks in advanced!
Jun 21 '10 #1
8 7017
johny10151981
1,059 1GB
You better Ask specifically what is your problem.
Jun 21 '10 #2
@johny10151981
To: johny10151981

the problem is that I cannot get the really position if I set the css style position to relative.
Jun 21 '10 #3
johny10151981
1,059 1GB
Use the function below
Expand|Select|Wrap|Line Numbers
  1. function getPosition(obj){
  2.     var topValue= 0,leftValue= 0;
  3.     while(obj){
  4.     leftValue+= obj.offsetLeft;
  5.     topValue+= obj.offsetTop;
  6.     obj= obj.offsetParent;
  7.     }
  8.     finalvalue = leftValue + "," + topValue;
  9.     return finalvalue;
  10. }
I got this small piece of code in some site but cant recall where.

First off all you can get any objects offset position. offset position is related to its parents position.
obj.offsetParent return the parent of the current object
Expand|Select|Wrap|Line Numbers
  1. <div id=d1>
  2.  <div id=d2>
  3.  </div>
  4. </div>
  5.  
in this above example d2's parents is d1. Top most parent id main window page. and Window's offset parent is no one i.e. null.

If anyof my above information is wrong please let me know.

Best Regards
johny
Jun 21 '10 #4
hi, johny, thanks for your reply!

I use your function before, and it doesn't work in IE. You can test the following code:

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <title>Test</title>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. <script type="text/javascript">
  6. function getPosition(obj){
  7.     var topValue = 0, leftValue = 0;
  8.     while(obj){
  9.         leftValue += obj.offsetLeft;
  10.         topValue += obj.offsetTop;
  11.         obj = obj.offsetParent;
  12.     }
  13.     return {left: leftValue, top: topValue};
  14. }
  15. function move(src, target) {
  16.     var position = getPosition(target);
  17.     src.style.top = position.top + "px";
  18.     src.style.left = position.left + "px";
  19. }
  20. </script>
  21. <style>
  22. #idText { border:1px red solid ; padding-left: 100px; }
  23. #mainDiv {
  24.     position: relative;
  25.     margin: 50px 0 0 200px;
  26.     border: 1px solid blue;
  27.     padding: 20px;
  28. }
  29. .marker {
  30.     position: absolute;
  31.     border:1px solid black;
  32. }
  33. #marker1 {
  34.     background-color:yellow;
  35. }
  36. #marker2 {
  37.     background-color:blue;
  38. }
  39. #marker3 {
  40.     background-color: #00FF00;
  41. }
  42. td {
  43.     width: 150px;
  44.     height: 70px;
  45. }
  46. </style>
  47. </head>
  48. <body>
  49. <div id="marker1" class="marker">1. moveToMainDiv</div>
  50. <div id="marker2" class="marker">2. moveToText</div><br />
  51. <div id="marker3" class="marker">3. moveToCell</div>
  52. <div id="mainDiv">
  53.     #### Main Div ####<div id="idText">a text</div>############
  54.     <br />
  55.     <table cellpadding="1" cellspacing="1" border="1"><tr>
  56.         <td onClick="getEditorPosition(this);">Cell1 - click me</td>
  57.         <td onClick="getEditorPosition(this);" >Cell2 - click me</td>
  58.     </tr></table>
  59. </div>
  60.  
  61. <script type="text/javascript">
  62.  
  63. var m1 = document.getElementById('marker1');
  64. var m2 = document.getElementById('marker2');
  65. var m3 = document.getElementById('marker3');
  66. var mainDiv = document.getElementById('mainDiv');
  67. var text = document.getElementById('idText');
  68.  
  69. move(m1, mainDiv);
  70. move(m2, text);
  71.  
  72. function getEditorPosition(cell) {
  73.     move(m3, cell);
  74. }
  75.  
  76.  
  77. </script>
  78. </body>
  79. </html>
  80.  
Jun 22 '10 #5
I updated my test scripts:

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.     <head>
  3.         <title>Test</title>
  4.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5.         <script type="text/javascript">
  6.             function getPosition(obj){
  7.                 var topValue = 0, leftValue = 0;
  8.                 while (obj) {
  9.                     leftValue += obj.offsetLeft;
  10.                     topValue += obj.offsetTop;
  11.                     obj = obj.offsetParent;
  12.                 }
  13.                 return {
  14.                     left: leftValue,
  15.                     top: topValue
  16.                 };
  17.             }
  18.         </script>
  19.         <style type="text/css">
  20.             * {
  21.                 border: 0;
  22.                 margin: 0;
  23.                 padding: 0;
  24.             }
  25.             #div1 {
  26.                 padding: 50px;
  27.             }
  28.             #div2 {
  29.                 position: relative;
  30.                 margin: 20px;
  31.                 padding: 50px;
  32.                 background: red;
  33.             }
  34.             #div3 {
  35.                 height: 50px;
  36.                 width: 400px;
  37.                 background: #ccc;
  38.                 padding: 20px;
  39.             }
  40.             #cursor {
  41.                 position: absolute;
  42.                 background-color: yellow;
  43.                 width: 50px;
  44.                 z-index: 1000;
  45.             }
  46.         </style>
  47.     </head>
  48.     <body>
  49.         <div id="div1">
  50.             <div id="cursor">Cursor</div>
  51.             <div id="div2">
  52.                 <br>div2<br><br>
  53.                 <div id="div3" onClick="moveCursor(this);">div3 - cursor should be moved to here</div>
  54.             </div>
  55.             <script type="text/javascript">
  56.                 var cursor = document.getElementById('cursor');
  57.                 var mainDiv = document.getElementById("div2");
  58.                    move(cursor, mainDiv);
  59.  
  60.                 function moveCursor(cell){
  61.                     var position = getPosition(cell);
  62.                     cursor.style.top = position.top + "px";
  63.                     cursor.style.left = position.left + "px";
  64.                 }
  65.             </script>
  66.         </div>
  67.     </body>
  68. </html>
  69.  
Jun 27 '10 #6
johny10151981
1,059 1GB
does your updated script work?
let me know, i am checking too
Jun 27 '10 #7
johny10151981
1,059 1GB
Javascript cannot find you move function on line 58
fix it. and test your javascript on firefox
Jun 27 '10 #8
Hi, johny10151981.

The updated script doesn't work, but you can try the below one: I use a new method in this script: getBoundingClientRect, it seems working fine both firefox and IE. (BTY, the script I posted just now, it works in firefox, but not IE)

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.     <head>
  3.         <title>Test</title>
  4.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5.         <script type="text/javascript">
  6.             function getPosition(obj){
  7.                 var topValue = 0, leftValue = 0;
  8.                 while (obj) {
  9.                     leftValue += obj.offsetLeft;
  10.                     topValue += obj.offsetTop;
  11.                     obj = obj.offsetParent;
  12.                 }
  13.                 return {
  14.                     left: leftValue,
  15.                     top: topValue
  16.                 };
  17.             }
  18.  
  19.             function getScroll(){
  20.                 var t, l, w, h;
  21.                 if (document.documentElement && document.documentElement.scrollTop) {
  22.                     t = document.documentElement.scrollTop;
  23.                     l = document.documentElement.scrollLeft;
  24.                     w = document.documentElement.scrollWidth;
  25.                     h = document.documentElement.scrollHeight;
  26.                 }
  27.                 else 
  28.                     if (document.body) {
  29.                         t = document.body.scrollTop;
  30.                         l = document.body.scrollLeft;
  31.                         w = document.body.scrollWidth;
  32.                         h = document.body.scrollHeight;
  33.                     }
  34.                 return {
  35.                     t: t,
  36.                     l: l,
  37.                     w: w,
  38.                     h: h
  39.                 };
  40.             }
  41.         </script>
  42.         <style type="text/css">
  43.             * {
  44.                 border: 0;
  45.                 margin: 0;
  46.                 padding: 0;
  47.             }
  48.  
  49.             #div1 {
  50.                 padding: 50px;
  51.             }
  52.  
  53.             #div2 {
  54.                 position: relative; /* this is for testing, if the position use offsetleft and offset right, this will cause bug */
  55.                 margin: 20px;
  56.                 padding: 50px;
  57.                 background: red;
  58.             }
  59.  
  60.             #div3 {
  61.                 height: 50px;
  62.                 width: 400px;
  63.                 background: #ccc;
  64.                 padding: 20px;
  65.             }
  66.  
  67.             #cursor {
  68.                 position: absolute;
  69.                 background-color: yellow;
  70.                 width: 50px;
  71.                 z-index: 1000;
  72.             }
  73.         </style>
  74.     </head>
  75.     <body>
  76.         <div id="div1">
  77.             <div id="cursor">
  78.                 Cursor
  79.             </div>
  80.             <div id="div2">
  81.                 <br>
  82.                 div2
  83.                 <br>
  84.                 <br>
  85.                 <div style="left: 50px; top: 100px; background: green; padding: 1500px  2em 0 1000px; ">
  86.                     <div id="div3" onClick="moveCursor(this);">
  87.                         div3 - cursor should be moved to here
  88.                     </div>
  89.                 </div>
  90.             </div>
  91.             <script type="text/javascript">
  92.                 var cursor = document.getElementById('cursor');
  93.                 var div2 = document.getElementById("div2");
  94.                 move(cursor, div2);
  95.  
  96.                 function moveCursor(cell){
  97.                     //var p = getPosition(cell);
  98.                     //cursor.style.top = p.top + "px";
  99.                     //cursor.style.left = p.left + "px";
  100.  
  101.                     var s = getScroll();
  102.                     var bcr = cell.getBoundingClientRect();
  103.                     cursor.style.top = (bcr.top + s.t) + "px";
  104.                     cursor.style.left = bcr.left + "px";
  105.                 }
  106.             </script>
  107.         </div>
  108.     </body>
  109. </html>
  110.  
Jun 27 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: philjhanna | last post by:
Hi, In the example code below can anyone tell me why the first link alerts an empty string but the second alerts the width? The only difference is the way the left: 20px; is applied but I...
0
by: Loane Sharp | last post by:
Hi there I am trying to display a dropdownlist, label and image in the foreground with a Flash animation in the background. I'm using the following code, which works for the dropdownlist but...
2
by: tpaulson | last post by:
I have a couple of DIV's that I hide/display based on radio buttons. On the DIV's, I have multiple drop down boxes. The source shows that they are populated, but I can't make them drop down. Only...
1
by: DJG79 | last post by:
Hi all, I am using an open source menu that i found and it works great, except for one thing that when the web page is not scrolled to the very top the drop down links will not stay visible. Has...
0
by: sge | last post by:
I have two <div> tags that both have embedded flash movie within the tags. I'd like them to be on top of each other. So when I hide one flash movie, the other one would show without being refreshed....
1
by: GGG | last post by:
Neither go the way I want them to... Absolute doesn't get it right over multiple browsers. Relative puts it in the right place, but only the portion that it is "relative" the style, #wleMenu, is...
0
by: crisscross27 | last post by:
Hi, I found a page called "myflashfetish" where you chan choose mp3 players for my space, well the problem is this, I wanted to place 2 or more players in myspace in a particular place, I read...
1
by: finizaini | last post by:
I'm receiving an "Object Expected" Error (Line:309, Char:0). I'm confused as to what is happening.Also, I can't run this code using other browser such as Fire Fox. Thispage only can view using IE....
3
by: suganya | last post by:
Hi Some professionals already has developed the project using menu. In my company, they have given me task to clear the error in that. It is a script file named as "menubarAPI4.js" which is kept...
2
by: tridirk | last post by:
Hi; I am getting a Objceted Expected Error on my forum site. I can't find what is wrong? Line: Char: Error: Object expected Code:0 the site is My SMF Forum
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.