I'm trying to create a custom cursor and detect the hover on some elements but the mouse enter and mouse leave event doesn't work properly when I uncomment the 2 lines in the mouse move event. However, It works when I delete the transform property of my cursor for an unkown reason.
I tried to subtract the half of the size of my cursor in my mouse move event, instead of having the transform property but I have the same result.
const cursor = document.querySelector(".cursor");
const elHover = document.querySelectorAll("img");
let mouse = {
x: undefined,
y: undefined,
};
document.addEventListener("mousemove", (e) => {
mouse.x = e.pageX;
mouse.y = e.pageY;
// cursor.style.top = e.pageY + "px";
// cursor.style.left = e.pageX + "px";
});
elHover.forEach((element) => {
element.addEventListener("mouseenter", (e) => {
// console.log("enter");
document.querySelector("body").style.backgroundColor = "red";
});
element.addEventListener("mouseleave", (e) => {
// console.log("leave");
document.querySelector("body").style.backgroundColor = "blue";
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background-color: #1d3557;
color: white;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
"Lucida Sans", Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
grid-gap: 10px;
}
.cursor {
width: 40px;
height: 40px;
position: absolute;
border-radius: 50%;
border: 2px white solid;
z-index: 999;
transform: translate(-50%, -50%);
}
<div class="gallery">
<img src="https://picsum.photos/200" alt="" />
<img src="https://picsum.photos/200" alt="" />
<img src="https://picsum.photos/200" alt="" />
<img src="https://picsum.photos/200" alt="" />
<img src="https://picsum.photos/200" alt="" />
<img src="https://picsum.photos/200" alt="" />
</div>
<div class="cursor"></div>
Add pointer-events:none
to cursor
element's css.
The pointer-events property allows for control over how HTML elements respond to mouse/touch events – including CSS hover/active states, click/tap events in Javascript, and whether or not the cursor is visible.
the prime use case for pointer-events is to allow click or tap behavior to “pass through” an element to another element below it on the Z axis.
Source - https://css-tricks.com/almanac/properties/p/pointer-events/