JSFiddle - React, Tailwind, and code Playground
by IanY
HTML
<div id="content"></div>
CSS
#content {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
width: 100px;
height: 100px;
background: lightblue;
}
JavaScript
// Modified from https://stackoverflow.com/a/15020514/1091014
document.querySelector('#content').onmouseleave = function(e) {
var edge = closestEdge(e.pageX, e.pageY, this.clientWidth, this.clientHeight);
console.log(edge);
}
function closestEdge(x,y,w,h) {
var topEdgeDist = distMetric(x,y,w/2,0);
var bottomEdgeDist = distMetric(x,y,w/2,h);
var leftEdgeDist = distMetric(x,y,0,h/2);
var rightEdgeDist = distMetric(x,y,w,h/2);
var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
switch (min) {
case leftEdgeDist:
return "left";
case rightEdgeDist:
return "right";
case topEdgeDist:
return "top";
case bottomEdgeDist:
return "bottom";
}
}
function distMetric(x,y,x2,y2) {
var xDiff = x - x2;
var yDiff = y - y2;
return (xDiff * xDiff) + (yDiff * yDiff);
}