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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS? #Jan 8 How to Install Xcode Command Line Tools on MacOS?
You might also like these
What is Etrieve Flow?MiscellaneousAdvanced nesting in Sass (SCSS) using at-rootSCSSWhat are Google Web Stories and How to create them in WordPress?WordPressHow to create a cross-browser smooth scrolling with jQuery?jQueryALTER DATABASE in PostgreSQLPostgresWhat is the difference between float and double?Miscellaneous