I’m trying to create a mouse cursor that uses an image instead of the default pointer.
I’ve created a class and set the cursor to point an image in my CSS;
/* CSS Basic Reset */
*, *::after, *::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
height: 100%;
}
body {
height: 100%;
}
.mouse-pointer {
cursor: url('/assets/images/cursor.png'), auto;
}
Then, I’m creating a logical division element with JavaScript, adding the 'mouse-pointer
class to it, and appending the mousePointer
element to the document.body
;
const mousePointer = document.createElement('div');
mousePointer.classList.add('mouse-pointer'); // Update to 'mouse-pointer'
document.body.appendChild(mousePointer);
I was expecting to see an image instead of the default mouse cursor, but I see nothing. I’m new to this, so I’m not sure what I’m doing wrong.
I’m not looking for solutions in JQuery, or anything else outside of vanilla JavaScript. I’m not looking to use CSS to accomplish this effect either.
Thanks.
2
Answers
The solution was more simple than I expected. Here's my solution.
That being said, this isn't the solution I was hoping for because it's not a solution to the specific problem I was having. The problem I had is still present, I'm just using something different to accomplish something similar.
If you’re looking to change the mouse cursor globally across the entire webpage using
JavaScript
without altering theCSS
for the wholebody
ordocument
directly, you need to set the cursor style at a higher level, ideally on the body or html tag.Here’s how you could do it directly with JavaScript: