I have a div that will be set according to the hovered element position in window. At first I thought this was a JQuery bug, but after more investigating and changing to vanilla, it's still the same.
I have created a code snippet to demonstrate my problem. If you mouse enter white div from top, the position is correct and orange box cover entire white box, but if you enter it from other sides, it's incorrect by few pixel:
var inspector_rect2= document.getElementById('inspector_rect');
$(window).mouseover(function(event) {
inspector_rect2.style.left= event.target.getBoundingClientRect().x+'px';
inspector_rect2.style.top= event.target.getBoundingClientRect().y+'px';
inspector_rect2.style.width= event.target.getBoundingClientRect().width+'px';
inspector_rect2.style.height= event.target.getBoundingClientRect().height+'px';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
</head>
<style>
html, body {
height : 100%;
margin : 0;
width : 100%;
}
.MyCSS {
background-color : silver;
}
.Container {
height : 100%;
margin : auto;
width : 50%;
}
.Header {
height : 5%;
padding : 2% 0;
width : 100%;
}
.MainContent {
background-color : white;
height : 70%;
width: 100%;
}
.inspector{
position: absolute;
pointer-events: none;
z-index: 999;
background: rgba(255, 166, 0, 0.5);
}
</style>
<body class="MyCSS">
<div class="Container" >
<div class="Header" ></div>
<div class="MainContent" ></div>
</div>
</body>
<div id=inspector_rect class=inspector></div>
It seems to be caused by an interaction between requesting .getBoundingClientRect() and setting width and height.
Generally, you should just make one request, store it, then re-use as needed.
$(window).mouseover(function(event) {
const rect = event.target.getBoundingClientRect();
inspector_rect2.style.left= rect.x+'px';
inspector_rect2.style.top= rect.y+'px';
inspector_rect2.style.width= rect.width+'px';
inspector_rect2.style.height= rect.height+'px';
});