Mihkel L.
Mihkel L.

Reputation: 1573

Add, don't replace, icon to mouse cursor

I want to add an icon to mouse when they hover html element, so that I could hint to the user, that they can right click.

I don't want to replace the default cursor, because they differ on platform and don't really need to replace the default mouse icon itself.

Upvotes: 0

Views: 196

Answers (1)

Spectric
Spectric

Reputation: 31987

You can add a mousemove event listener on the element which you want to show the custom cursor over that gets the relative x and y coordinates of the mouse to the element and applies them to the top and left style properties of the cursor:

element.addEventListener('mousemove', function(e){
  const rect = element.getBoundingClientRect();
  const [x, y] = [e.pageX - rect.left, e.pageY - Math.abs(rect.top) + window.scrollY]
  cursor.style.display = "block";
  cursor.style.left = x + "px";  
  cursor.style.top = y + "px";
})

element.addEventListener('mouseleave', function(e){
  cursor.style.display = "none"; //hide the custom cursor when they leave the element
})
#element{
  height:1200px;
  width:600px;
  background-color:black;
  position:relative;
}

#cursor{
  position:absolute;
  display:none;
  color:white;
}
<div id="element"><div id="cursor">right click!</div></div>

Keep in mind this solution requires the container element to be relatively positioned, since the cursor is absolutely positioned.

Upvotes: 1

Related Questions