I’m trying to make a custom cursor image so it can replace my actual cursor in certain section. What i would like to achieve is to show the image when inside the section and make it disappear when section is left. I managed to display it correctly while being in the section but going outside does not hide it. What am I doing wrong?
const box = document.querySelector(".box");
const customCursor = document.createElement("img");
customCursor.style.width = "175px";
customCursor.style.height = "175px";
customCursor.style.position = "absolute";
customCursor.src = "https://picsum.photos/175";
customCursor.style.display = "none";
box.appendChild(customCursor);
box.addEventListener("mousemove", (e) => {
customCursor.style.display = "block";
customCursor.style.left = `${e.pageX - customCursor.width / 2}px`;
customCursor.style.top = `${e.pageY - customCursor.height / 2}px`;
});
box.addEventListener("mouseleave", () => {
customCursor.style.display = "none";
});
body {
font-family: sans-serif;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
cursor: none;
width: 100%;
padding: 5rem;
background-color: lightblue;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<div class="box"></div>
</div>
<script src="src/index.js"></script>
</body>
</html>
Leaving a sandbox link as well – https://codesandbox.io/s/javascript-forked-6v9rcm?file=/src/index.js
2
Answers
The issue can be resolved by changing your events listeners. If you use mouseover and mouseout you’ll have a better time.
Based on Ouroborus comment
You have to add
pointer-events: none
to your img