perkiset
There are many times that I want to absolutely position something, but in a relative position to something else on the page. Ergo, I need to find the top and left px value for an element I'll use as the "anchor" - but based on the way the DOM tree is laid out, I need to add together the offsets of all the parent nodes that "own" me to get the right values. Here is the code I use.
[ I'll be using this code in my Argument Against Ajaxpost as well... ]Note that this expects you to pass a reference to a node, so you might use it like this: var myElement = document.getElementById('myElement'); var top = getElementTop(myElement); function getElementLeft(obj) { var curleft = 0; if(obj.offsetParent) { while(true) { curleft += obj.offsetLeft; if(!obj.offsetParent) { break; } obj = obj.offsetParent; } } else if(obj.x) { curleft += obj.x; } return curleft; } function getElementTop(obj) { var curtop = 0; if(obj.offsetParent) { while(true) { curtop += obj.offsetTop; if(!obj.offsetParent) { break; } obj = obj.offsetParent; } } else if(obj.y) { curtop += obj.y; } return curtop; } |
Thread Categories
Best of The Cache Home | ||
Search The Cache |
- Ajax
- Apache & mod_rewrite
- BlackHat SEO & Web Stuff
- C/++/#, Pascal etc.
- Database Stuff
- General & Non-Technical Discussion
- General programming, learning to code
- Javascript Discussions & Code
- Linux Related
- Mac, iPhone & OS-X Stuff
- Miscellaneous
- MS Windows Related
- PERL & Python Related
- PHP: Questions & Discussion
- PHP: Techniques, Classes & Examples
- Regular Expressions
- Uncategorized Threads