Cross-browser javascript function to find actual position of an element in page
html, internet-explorer, javascript
Solution
This independent piece of code should get you the offset in modern browsers, without frameworks. It uses the `getBoundingClientRect` method:
function offset(element){
var body = document.body,
win = document.defaultView,
docElem = document.documentElement,
box = document.createElement('div');
box.style.paddingLeft = box.style.width = "1px";
body.appendChild(box);
var isBoxModel = box.offsetWidth == 2;
body.removeChild(box);
box = element.getBoundingClientRect();
var clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || isBoxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || isBoxModel && docElem.scrollLeft || body.scrollLeft;
return {
top : box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft};
}
Problem
SORRY - MY BAD - There was error in another script that made me think this function is buggy. ** * but hey, you've got a nice function if you need one ;) Thanks for help guys. !~~ I got this function: ``` function findPos(obj) { var curleft = curtop = 0; if (obj && obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; } ``` to find and element's actual position in page. But for some reason, it throws me an error in IE; how do I fix this to work cross-browser?