I got this mouseover effect that you can see on this CodePen.
The cursor is always red, but I want it to change into a bigger (scaled) white cursor when it hovers one of the items.
<div class="custom-cursor"></div>
(this is the cursor div
, it’s always red and via JS I make this div
follow my cursor around).
And then we have our elements:
<div class="row-02-rig-sin black-cursor">
...
</div>
This above is the <div>
where I want the cursor to change shape and color. To do that, I made an eventListener
so that I can track when the mouse goes over the class name of .black-cursor
. Here is the JS code for that:
document.addEventListener("mouseover", function (e) {
if (e.target.matches(".black-cursor")) {
customCursor.classList.add("is-hovering");
}
});
The code above "should" work (and it does partially) when you hover over the div
, but the problem is that the e.target.matches()
is not triggering when the cursor is hovering on an element that is inside the .black-cursor
.
With simple CSS I change the cursor when it is hovering over .black-cursor
since there is customCursor.classList.add("is-hovering");
when it returns true.
.custom-cursor.is-hovering {background-color:#fff;width:70px;height:70px;}
Try to play around in the CodePen, with the cursor place exactly ontop of the black horizontal bar. This is the only place that the e.target
is equal to the correct element, so it triggers there, but nowhere else.
An easy fix would be to track if the e.target
is a children of a .black-cursor
parent. Or also, I could add the class name .black-cursor
on each element so that I can ensure the cursor works. But I don’t like both of these solutions. The 1st one is time consuming for the end-user due to the calculations while mousemove
and the 2nd solution is time consuming for the developer to add the same class name to all the elements.
Is there some other solution with priority on the performance? So no lags, no fps drops would appear. I’ve heard of a requestAnimationFrame
here and there but I haven’t tried that yet since I dont know if it would help me.
2
Answers
CodePen is update with the correct code:
This was replaced...
...with this:
You need to make your mouseout code smarter so it is not removing the class every time it is called.
This solution is still not perfect, but should give you a starting point.