I have a stage (id="box"), when the cursor moves on this stage, a red circle will moves along with the cursor. Everything works as expects, but the cursor is outside of the red circle.
I try to get the cursor stays in center the circle, but not successful, yet.
Any help would be appreciated!
$("#box").mousemove( function(e) {
$popup = $(this).find(".circle").first();
var eTop = $(this).offset().top;
var eLeft = $(this).offset().left;
var x = e.pageX;
var y = e.pageY;
// console.log("pageX: " + x);
// console.log("pageY: " + y)
$(this).find(".circle").css({top: y - eTop, left: x - eLeft });
});
#box {
width:500px;
height:200px;
display:block;
background: green;
position:relative;
}
.circle {
position: absolute;
z-index: 100;
overflow:hidden;
white-space: nowrap;
border: 1px solid red;
width: 100px;
height: 100px;
border-radius: 100%
}
#box .circle {visibility: hidden;}
#box:hover .circle {visibility: visible;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="box">
<div class="circle"></div>
</div>
2
Answers
You forgot to subtract the circle radius from its coordinates:
I think it’s simpler to use a css translation(x,y), and it avoids repeating calculations unnecessarily…