JSFiddle - React, Tailwind, and code Playground
by gregborbonus
HTML
<div id="test">
</div>
<div id="testsq">
</div>
CSS
#test{
border:1px solid black;
width:100px;
height:100px;
margin:50px;
margin-top:58px;
}
#testsq{
border:1px solid blue;
width:10px;
height:10px;
position:absolute;
top:8px;
left:8px;
}
JavaScript
mousePos = {x:0,y:0};
document.addEventListener('mousemove', function(e){
mousePos.x = e.pageX;
mousePos.y = e.pageY;
updateSquare();
});
function updateSquare(){
sqLeft=53;
sqTop=53;
XY=100;
inside=false;
if(mousePos.x > sqLeft && mousePos.x < (sqLeft + XY)){
X=mousePos.x;
inside=true;
}else{
if(mousePos.x < sqLeft){
X=sqLeft;
}else{
X=sqLeft + XY;
}
}
if(mousePos.y > sqTop && mousePos.y < (sqTop + XY)){
Y=mousePos.y;
indside=true;
}else{
if(mousePos.y < sqTop){
Y=sqTop;
}else{
Y=sqTop + XY;
}
}
if(inside && X < sqLeft+XY && X > sqLeft && Y < sqTop+XY && Y > sqTop ){
//Here we are strictly inside, so lets figure out the max and use that as our default factor.
max=Math.max(X,Y);
if(X == max){
//Set Y to whichever is closer to the current Y.
if((Y-sqTop) < ((sqTop+XY) - Y)){
Y=sqTop;
}else{
Y=sqTop+XY;
}
}else{
if((X-sqLeft) < ((sqLeft+XY) - X)){
X=sqLeft;
}else{
X=sqLeft+XY;
}
}
}
console.log(X,Y);
document.getElementById('testsq').style.top=Y + 'px';
document.getElementById('testsq').style.left=X + 'px';
}