I’ve a problem with a custom cursor created with an absolute div, with my test I realized that the custom div is directly positioned under the default cursor, then if I go hover a link I can’t process my JS “mouseenter” because the default cursor is always hover only to the custom cursor… there is a way to fix it?
<div class="custom-cursor"></div>
Scss:
.custom-cursor { width: 20px; height: 20px; border: 2px solid orange; position: absolute; z-index: 1080; border-radius: 50%; transition-duration: 100ms; transition-timing-function: ease-out; box-shadow: 0 0 0 2px black; &.hover { width: 40px; height: 40px; background: rgba(#FFCC00,.5); } }
Vanilla JS:
const cursor = document.querySelector('.custom-cursor'); // Custom cursor follow the default cursor document.addEventListener('mousemove', e => { cursor.setAttribute('style', 'top: '+(e.pageY - 10)+'px; left: ' +(e.pageX - 10)+'px;') }); const links = document.querySelectorAll('a'); // Custom cursor change style on hover links for(let x of links) { x.addEventListener('mousenter', () => { cursor.classList.add('hover'); }); x.addEventListener('mouseleave', () => { cursor.classList.remove('hover'); }); });
Advertisement
Answer
You can use pointer-events: none;
for the cursor-div – so that the hover event goes through. (you also forgot an e in “mouseenter“
Working example:
const cursor = document.querySelector('.custom-cursor'); // Custom cursor follow the default cursor document.addEventListener('mousemove', e => { cursor.setAttribute('style', 'top: '+(e.pageY - 10)+'px; left: ' +(e.pageX - 10)+'px;') }); const links = document.querySelectorAll('a'); // Custom cursor change style on hover links for(let x of links) { x.addEventListener('mouseenter', () => { cursor.classList.add('hover'); }); x.addEventListener('mouseleave', () => { cursor.classList.remove('hover'); }); }
.custom-cursor { width: 20px; height: 20px; border: 2px solid orange; position: absolute; border-radius: 50%; transition-duration: 100ms; transition-timing-function: ease-out; box-shadow: 0 0 0 2px black; pointer-events: none; } .custom-cursor.hover { width: 40px; height: 40px; background: rgba(#FFCC00,.5); }
<div class="custom-cursor"></div> <a href="#">troet</a> <a href="#">quak</a> <a href="#">miau</a>