I\'m trying to simulate the effect where I hover on an image an overlayed semi-transparent image will fade in from the direction where your mouse came from. Vice versa when your
This is a simple solution, but the edges need improvements in mouseenter event.
In mouse enter event I gave it 5% differ in (0% & 0%) (100% & 100%) just for catching the cursor if it moves fast and this is the bug that needs a fix.
const div = document.querySelector('div');
const mouseLeave = (e) => {
e.preventDefault();
e = e || window.event;
// get box properties
let a = e.target.getBoundingClientRect();
let w = a.width;
let h = a.height;
// get x,y
const x = e.pageX - a.left;
const y = e.pageY - a.top;
//* detect mouse out
if (x >= w) console.log('out-right');
if (x <= 0) console.log('out-left');
if (y >= h) console.log('out-bottom');
if (y <= 0) console.log('out-top');
}
const mouseEnter = (e) => {
e.preventDefault();
e = e || window.event;
// get box properties
let a = e.target.getBoundingClientRect();
let w = a.width;
let h = a.height;
// get x,y
const x = e.pageX - a.left;
const y = e.pageY - a.top;
// get positions by percentage
const X = (x / w) * 100;
const Y = (y / h) * 100;
//* detect mouse in
if ((X >= 0 && X <= 100) && (Y >= 0 && Y <= 5)) console.log('in-top');
if ((X >= 0 && X <= 100) && (Y >= 95 && Y <= 100)) console.log('in-bottom');
if ((Y >= 0 && Y <= 100) && (X >= 95 && X <= 100)) console.log('in-right');
if ((Y >= 0 && Y <= 100) && (X >= 0 && X <= 5)) console.log('in-left');
}
div.addEventListener('mouseleave', mouseLeave, true);
div.addEventListener('mouseenter', mouseEnter, true);
div {
width: 300px;
height: 300px;
outline: 1px solid blue;
margin: 50px auto;
}