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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #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
You might also like these
Unary Operators in JavaScriptJavaScriptThe ALPHA function in Envision BasicEnvision BasicHow to Install Xcode Command Line Tools on MacOS?MiscellaneousCanvas Drawing in HTML5HTMLHow to Create a Copy of a Table in SQL and MySQL?SQL/MySQLWhat’s a Strict mode in JavaScript?JavaScript