Add Custom Cursor with CSS and JavaScript.

GURVINDER MAAN
2 min readSep 15, 2021

--

In this story we will get to know about how to add custom cursor ona website with help of HTML, CSS and JavaScript.

Make a div with class of .cursor or with the class of your choice :-

<div class=”cursor”></div>

Add styling to class .cursor :-

.cursor {
width: 20px;
height: 20px;
border: 1px solid black;
border-radius: 50%;
position: absolute;
}

This is an example of simple circle cursor, you can add your own styling of what type of custom cursor you want.

Add JavaScript to move the custom cursor on mouse position:-

Select the custom cursor div: -

const cursor = document.querySelector(“.cursor”);

Add an eventListener ‘mousemove’ on document :-

document.addEventListener(“mousemove”, (e) => {cursor.setAttribute(“style”, “top:” + (e.pageY — 10) + “px; left:” + (e.pageX — 10) + “px”);});

In the above eventListener we added the position top to e.pageY and left to e.pageX with the help of setAttribute() method of javaScript, which is the position of mouse from top and left of the page.

Added -10 to align the custom cursor to center of original cursor.

So wherever mouse moves our div with .cursor class moves on that position.

We can add styling to how our cursor behaves on click:-

.expand {animation: cursorAnim 0.5s forwards;
border: 1px solid black;
}@keyframes cursorAnim {0% {
transform: scale(1);
}
50% {
transform: scale(3);
}
100% {
transform: scale(1);
opacity: 0;
}
}

On click we will add this .expand class with help of JavaScript, which has animation to scale cursor to 3 and then back to 1 on click :-

document.addEventListener(“click”, () => {            cursor.classList.add(“expand”);            setTimeout(() => {
cursor.classList.remove(“expand”);
}, 500);
});

In above code we have add eventListener on click and added class expand on click event, and with the help of setTimeout() method we removed the same class after 5ms, to get the cursor to normal state.

You can add cursor none to hide the original cursor:-

body { cursor: none}

So this was just a simple circle custom cursor, we can add many more functionalities and animations to custom cursor with help of javaScript and css.

--

--

No responses yet