I'm trying to get the bounding rectangle for different elements. I get the rect for the element using getClientRects and then draw a red div over the rect. On firefox it works, but in chrome and safari I get weird results. On jsfiddle on safari it works but the same code in safari directly does not so it's difficult to show the problem.
http://jsfiddle.net/pmnwjc33/5/
On safari if I try to find the bounding boxes for an image and an input I get that the image has rectangle of 8,8,8,8 for top,left,bottom,right. So the bounding box for the image is not correct and that seems to throw off any bounding boxes after the image. Is there some way to make this work correctly?
Red Boxes are the rectangles
<html>
<body>
<input id="cart1" type=button value="AddToCart" ><br>
<img id="dogimage" src="http://www.petyourdog.com/uploads/articles/17-6.jpg">
<input id="cart2" type=button value="AddToCart2" ><br>
</body>
</html>
<script>
function addClientRectsOverlay(elt) {
console.log(elt.tagName);
// Absolutely position a div over each client rect so that its border width
// is the same as the rectangle's width.
// Note: the overlays will be out of place if the user resizes or zooms.
var rects = elt.getClientRects();
console.log(rects.length);
for (var i = 0; i != rects.length; i++) {
var rect = rects[i];
console.log(rect);
if(elt.tagName=="IMG"){
console.log(rect.top);
console.log(rect.bottom);
console.log(rect.right);
console.log(rect.left);
console.log(parseInt(rect.right)-parseInt(rect.left));
console.log(parseInt(rect.bottom)-parseInt(rect.top));
}
var tableRectDiv = document.createElement('div');
tableRectDiv.style.position = 'absolute';
tableRectDiv.style.border = '1px solid red';
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
tableRectDiv.style.margin = tableRectDiv.style.padding = '0';
tableRectDiv.style.top = (rect.top) + 'px';
tableRectDiv.style.left = (rect.left) + 'px';
// we want rect.width to be the border width, so content width is 2px less.
tableRectDiv.style.width = (rect.width - 2) + 'px';
tableRectDiv.style.height = (rect.height - 2) + 'px';
document.body.appendChild(tableRectDiv);
}
}
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].tagName!="BR"){
addClientRectsOverlay(all[i]);
}
}
</script>
The getClientRects method is supported in Firefox from version 3, in Opera from version 9.5 and in Safari from version 4.
Hence, it doesn't work in Chrome.