Custom animated cursor : HTML, CSS, JS

ยท

2 min read

Custom animated cursor : HTML, CSS, JS

Table of contents

No heading

No headings in the article.

We're going to learn how to customize our cursor using only HTML, CSS and JS. It's pretty simple to customize the cursor.

HTML

Select the cursor

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

CSS

Step 1 - First make the cursor disappear. Using universal selector.

* {
  cursor: none;
}

Step 2 -

Select the cursor and apply some style on it

.cursor {
    z-index: 999; // as high as you want it because we don't want our content to overlap our cursor
    position: fixed; 
    background: #2696e8;
    width: 1em;
    height: 1em;
    border-radius: 50%; 
    pointer-events: none;
    animation: colors 5s infinite;
    transform: translate(-50%, -50%);
    display: none;
}

Step 3 -

Add keyframes

@keyframes colors {
    0% {
        filter: hue-rotate(0deg);
    }
    100% {
        filter: hue-rotate(360deg);
    }
}

Step 4 -

Now's the time for our cursor to be better. Using pseudo element.

.cursor:before {
    content: "";
    position: absolute;
    background: #2696e8;
    width: 36px;
    height: 36px;
    opacity: 0.2;
    transform: translate(-30%, -30%);
    border-radius: 50%;
}

JavaScript

Our cursor won't be going places without the help of JavaScript, sadly it can't be CSS only.

const cursor = document.querySelector(".cursor");
var timeout;

//follow cursor on mousemove
document.addEventListener("mousemove", (e) => {
    let x = e.pageX;
    let y = e.pageY;

    cursor.style.top = y + "px";
    cursor.style.left = x + "px";
    cursor.style.display = "block";

    //cursor effects when mouse stopped
    function mouseStopped() {
        cursor.style.display = "none";
    }
    clearTimeout(timeout);
    timeout = setTimeout(mouseStopped, 1000);
});

Did you find this article valuable?

Support Aryan Srivastava by becoming a sponsor. Any amount is appreciated!

ย