There seems to be a thin 2px border surrounding the document viewport in some versions of Internet Explorer. This issue is not present in other browsers, making it challenging to calculate mouse positions accurately for the page and client areas. Initially, I attempted to address this by subtracting 2 from each calculation to adjust for the border.
However, after testing in various versions of IE and different IE embedding programs, I discovered that there are cases where no border exists. Therefore, simply checking for IE and subtracting 2 will not suffice.
Is there a reliable way to determine if the document viewport has a border in IE?
Example1: How to find the mouse position inside an object
<html>
<head>
<script>
var isIE = (!window.addEventListener);
window.onload = function(){
var foo = document.getElementById('foo');
if (isIE) foo.attachEvent('onmousemove',check_coords);
else foo.addEventListener('mousemove',check_coords,false);
}
function check_coords(e){
var foo = document.getElementById('foo');
var objPos = getPos(foo);
if (isIE) mObj = [window.event.clientX+document.body.scrollLeft-objPos[0], window.event.clientY+document.body.scrollTop-objPos[1]];
else mObj = [e.pageX-objPos[0], e.pageY-objPos[1]];
foo.innerHTML = mObj;
}
function getPos(obj){
var pos = [0,0];
while (obj.offsetParent){
pos[0] += obj.offsetLeft;
pos[1] += obj.offsetTop;
obj = obj.offsetParent;
}
return pos;
}
</script>
<style>
body{
margin:0px;
padding:0px;
}
#foo{
border:3px solid black;
position:absolute;
left:30px;
top:52px;
width:300px;
height:800px;
background-color:yellow;
}
</style>
</head>
<body>
<div id='foo'>Test test</div>
</body>
</html>
At coordinate [0,0], Internet Explorer (versions with the border) returns [2,2]
Example2: Determining scrollbar width
alert(screen.width-document.body.clientWidth);
For instance, with a scrollbar width of 17px, Internet Explorer (versions with the border) returns 21px without taking into account the 2px border on each side.
UPDATE:
After further investigation, it turns out that the 2px border was actually a default style applied to the body tag. Apologies for the confusion earlier! To correctly obtain the viewport border without altering the page (this applies specifically to IE calculations), you should use .currentStyle['borderWidth']
. It appears that the script functions properly in all other browsers without requiring a border check. When subtracting border-widths, ensure you consider both borderTopWidth
AND borderLeftWidth
.
In conclusion, I have awarded the bounty to Samuel for being the first to suggest that it might be a default browser style causing the border.