Custom Cursor in JavaScript and CSS (Code + Demo)

In this article you will know how to create Custom Cursor using JavaScript. You can enhance the user experience of your website by using JavaScript Custom Cursor. This is a step by step tutorial where I will show you how to create a Custom Cursor using HTML, CSS and JavaScript.

Custom cursors present an exciting opportunity to enhance user experience and express creativity in web design. By combining CSS for styling and JavaScript for interactivity, developers can create engaging cursor effects that captivate and delight users.

# Table of Contents

Custom Cursor in JavaScript and CSS

Custom cursors offer a unique opportunity to inject personality and interactivity into web interfaces. Instead of settling for the default arrow, designers can tailor the cursor to match the theme and purpose of their website or application. 

Whether it’s a sleek minimalist design, a playful animation, or a custom icon representing a specific function, the cursor can convey information and engage users in unexpected ways.

See the Pen Untitled by Shantanu Jana (@Shantanu-Jana-the-encoder) on CodePen.

Hope you liked the above Custom Mouse Cursor with CSS and JavaScript design. I have given the preview above, if you want the source code then you can use the download button below the article.

Step 1: Basic structure of Custom Cursor

The foundation of any JavaScript custom cursor begins with the HTML markup. Here, we define the elements that will serve as the cursor and its accompanying animations or effects.

<div id="cursor"></div>
<div id="cursor-border"></div>

Step 2: CSS Code of Custom Mouse Cursor

CSS is instrumental in defining the appearance and behavior of custom cursors. It allows for precise control over size, shape, color, and animation.

* {
  margin: 0;
  cursor: none;
}

body {
  background-color: #4578e1;
  height: 100vh;
  overflow: hidden;
}

#cursor {
  position: absolute;
  background-color: #fff;
  height: 10px;
  width: 10px;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
}

#cursor-border {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: transparent;
  border: 1px solid #fff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
  transition: all 0.2s ease-out;
}

Step 3: JavaScript code for Custom Cursor

JavaScript adds interactivity and dynamic behavior to custom mouse cursors. It tracks mouse movements and updates the cursor’s position accordingly.

// Get references to the cursor and cursor border elements from the DOM
const cursor = document.getElementById('cursor');
const cursorBorder = document.getElementById('cursor-border');

// Initialize variables to track cursor position and border position
let cursorX = 0,
  cursorY = 0,
  borderX = 0,
  borderY = 0;

// Variable to store the type of device (touch or mouse)
let deviceType = '';

// Function to check if it is a touch device
const isTouchDevice = () => {
  try {
    document.createEvent('TouchEvent');
    deviceType = 'touch'; // Set deviceType to 'touch' if touch event creation is supported
    return true;
  } catch (e) {
    deviceType = 'mouse'; // Set deviceType to 'mouse' if touch event creation is not supported
    return false;
  }
};

// Function to move the cursor
const move = (e) => {
  // Determine cursor position based on whether it's a touch or mouse event
  cursorX = !isTouchDevice() ? e.clientX : e.touches[0].clientX;
  cursorY = !isTouchDevice() ? e.clientY : e.touches[0].clientY;

  // Update cursor position in CSS
  cursor.style.left = `${cursorX}px`;
  cursor.style.top = `${cursorY}px`;
};

// Event listener for mousemove event
document.addEventListener('mousemove', (e) => {
  move(e); // Call move function to update cursor position
});

// Event listener for touchmove event
document.addEventListener('touchmove', (e) => {
  move(e); // Call move function to update cursor position
});

// Prevent default behavior on touchend to avoid unwanted scrolling or zooming
document.addEventListener('touchend', (e) => {
  e.preventDefault();
});

// Function to animate the border around the cursor
const borderAnimation = () => {
  const gapValue = 5; // Gap value determines the smoothness of animation

  // Calculate new border position based on cursor position
  borderX += (cursorX - borderX) / gapValue;
  borderY += (cursorY - borderY) / gapValue;

  // Update border position in CSS
  cursorBorder.style.left = `${borderX}px`;
  cursorBorder.style.top = `${borderY}px`;

  // Request animation frame to continuously update border position
  requestAnimationFrame(borderAnimation);
};

// Initiate border animation
requestAnimationFrame(borderAnimation);

Hope you like this project (How to Create a Custom House Cursor with CSS or JavaScript). I have shared many more mouse move effect tutorials like this before.

By leveraging the capabilities of HTML, CSS, and JavaScript, custom cursors can transform mundane interactions into memorable moments, leaving a lasting impression on website visitors.

Creating a custom mouse cursor with CSS and JavaScript involves a few steps. Below is a simple example to get you started:

HTML:

<div class=“container”> <h1>Move your mouse to see the custom cursor!</h1> </div>

CSS:

body {
cursor: none; /* Hide the default cursor */
}

.custom-cursor {
position: fixed;
width: 30px;
height: 30px;
background-image: url(‘cursor.png’); /* Replace ‘cursor.png’ with your custom cursor image */
background-size: cover;
pointer-events: none; /* Make sure the custom cursor doesn’t interfere with mouse events */
}

JavaScript:

document.addEventListener(‘DOMContentLoaded’, function () {
const cursor = document.querySelector(‘.custom-cursor’);

document.addEventListener(‘mousemove’, function (e) {
cursor.style.left = e.pageX + ‘px’;
cursor.style.top = e.pageY + ‘px’;
});
});

This code sets up a simple custom cursor that follows the mouse movements on the webpage. The cursor is defined in CSS, and its position is updated using JavaScript based on the mouse movements.

Creating a custom cursor using Vanilla JavaScript involves manipulating the DOM and handling mouse events. Below is a simple example of how you can achieve this:

<!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 {
margin: 0;
overflow: hidden; /* Ensure cursor can move anywhere on the page */
}
.custom-cursor {
position: fixed;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: rgba(255, 0, 0, 0.5);
pointer-events: none; /* Ensure cursor doesn’t interfere with underlying elements */
z-index: 9999; /* Ensure cursor stays on top */
transition: transform 0.1s ease;
}
</style>
</head>
<body>
<div class=”custom-cursor”></div>

<!– Your HTML content goes here –>

<script>
const cursor = document.querySelector(‘.custom-cursor’);

document.addEventListener(‘mousemove’, e => {
// Update cursor position
cursor.style.left = `${e.clientX}px`;
cursor.style.top = `${e.clientY}px`;
});

// Optional: Change cursor appearance when hovering certain elements
const hoverElements = document.querySelectorAll(‘.hover-effect’);

hoverElements.forEach(element => {
element.addEventListener(‘mouseenter’, () => {
cursor.classList.add(‘hovering’);
});

element.addEventListener(‘mouseleave’, () => {
cursor.classList.remove(‘hovering’);
});
});
</script>
</body>
</html>

Remember to replace <!-- Your HTML content goes here --> with your actual HTML content. Additionally, you can adjust the styles and functionality as needed for your specific use case.

Let’s explore a few more examples of custom cursors created purely with CSS. You can animate your custom cursor using CSS animations for a more dynamic effect. Here’s an example:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Custom Cursor with CSS Animation</title>
<style>
body {
margin: 0;
overflow: hidden;
}

/* Hide default cursor */
body {
cursor: none;
}

/* Define custom cursor with animation */
.custom-cursor {
position: fixed;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: rgba(255, 0, 0, 0.5);
pointer-events: none;
z-index: 9999;
animation: pulse 1s infinite alternate;
}

@keyframes pulse {
0% {
transform: scale(1);
}
100% {
transform: scale(1.2);
}
}

/* Optional: Change cursor appearance when hovering certain elements */
.hover-effect {
cursor: pointer; /* Change cursor to pointer when hovering */
}
</style>
</head>
<body>
<div class=”custom-cursor”></div>

<!– Your HTML content goes here –>
<div class=”hover-effect”>Hover me</div>

<script>
const cursor = document.querySelector(‘.custom-cursor’);

document.addEventListener(‘mousemove’, e => {
// Update cursor position
cursor.style.left = `${e.clientX}px`;
cursor.style.top = `${e.clientY}px`;
});
</script>
</body>
</html>

In this example, the custom cursor is animated using a CSS animation called pulse. You can adjust the animation duration, timing, and other properties to achieve the desired effect

Leave a Comment

Home
Menu
Instagram
Search