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.
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Keep in mind this solution requires the container element to be relatively positioned, since the cursor is absolutely positioned.