Yogesh Chauhan's Blog

How to create a circle that follows a cursor using JavaScript and CSS?

in CSS & JavaScript on August 3, 2021

In some dark theme mode a large cursor really helps identifying different elements on a page.

You can also differentiate the element with a different color when the cursor is on a specific element, which you can do that with a normal cursor too. The end goal is to widen the cursor area.

Let’s dive into it.

HTML

A simple div element is sufficient.


<div class='cursor' id="cursor"></div>


CSS

Pay attention to mix-blend-mode property. The value is set to difference which is helpful for dark and light both mode.


.cursor {
  position: fixed;
  border-radius: 50%;
  transform: translateX(-50%) translateY(-50%);
  pointer-events: none;
  left: -100px;
  top: 50%;
  mix-blend-mode: difference;
  background-color: white;
  z-index: 10000;
  border: 2px solid white;
  height: 30px;
  width: 30px;
  transition: all 300ms ease-out;
}


JavaScript

Now, lets add an event listener on body itself that will keep track of the cursor position and based on that, it’ll adjust the circle’s position.


var cursor = document.getElementById("cursor");
document.body.addEventListener("mousemove", function(e) {
  cursor.style.left = e.clientX + "px",
    cursor.style.top = e.clientY + "px";
});


Demo


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Forcing the domain to serve securely using HTTPSMiscellaneousHow to embed YouTube or other video links in WordPress?WordPressHow to create an empty array in Swift?SwiftHow to create a Child Theme in WordPress?WordPressHow to add a scroll back to top button using JavaScript and CSS?CSSA complete diagram with building blocks of an Angular applicationAngular