Introduction
Have you ever come across a website with a unique and eye-catching cursor?
Custom cursors offer a brilliant opportunity to infuse your web projects with personality and interactivity. Implementing a custom cursor not only elevates the user experience but also serves as an expression of your brand’s personality.
In this blog, we will learn the steps of creating a custom cursor using HTML, CSS and JavaScript.
Let’s start!
Set Up Your HTML File
Let’s create a basic HTML structure to start with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Cursor</title>
</head>
<body>
<!-- To create the cursor -->
<div class="cursor"></div>
</body>
</html>
Add CSS
Next, let’s add CSS to style the custom cursor.
body {
cursor: none; /* Hide the default cursor */
}
.cursor {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: green;
border-radius: 50%;
pointer-events: none; /* Ensure the custom cursor doesn't interfere with content */
}
Implement JavaScript
Now for the cursor to work with the user’s mouse movement, we have to implement JavaScript.
// Get the cursor
const cursor = document.querySelector(".cursor");
document.addEventListener("mousemove", function (e) {
cursor.style.left = e.clientX + "px";
cursor.style.top = e.clientY + "px";
});
Putting It All Together
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Custom Cursor</title>
<style>
body {
cursor: none; /* Hide the default cursor */
}
.cursor {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: green;
border-radius: 50%;
pointer-events: none; /* Ensure the custom cursor doesn't interfere with content */
}
</style>
</head>
<body>
<!-- To create the cursor -->
<div class="cursor"></div>
<script>
// Get the cursor
const cursor = document.querySelector(".cursor");
document.addEventListener("mousemove", function (e) {
cursor.style.left = e.clientX + "px";
cursor.style.top = e.clientY + "px";
});
</script>
</body>
</html>
That’s it! Save your files and open the HTML file in your web browser. You should now see your custom cursor in action.
Thanks for reading.
For more content like this click here!
Top comments (0)