Make a animated mouse follower



Ever felt a website needed a touch of whimsy? Animated elements that react to user interaction can add a layer of fun and engagement. In this blog post, we'll delve into creating an animated "mouse follower" using the power trio of HTML, CSS, and JavaScript!




What is a Mouse Follower?

Imagine a playful element on your website that follows your mouse cursor around the screen. This is a mouse follower! It can be anything from a cute character to a subtle geometric shape, adding a dynamic touch to your design.

Here is how to do it:-

HTML-

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<link
href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css"
rel="stylesheet"
/>
<title>mouse follower</title>
</head>
<body>
<div class="mouse-follower"> </div>
</body>
Thats all you need for the html. The real magic happens in css and js.


CSS:


.mouse-follower {
height: 2.1rem;
aspect-ratio: 1;
border-radius: 50%;
background: transparent;
border: 2.5px solid #6c99b2;
position: fixed;
left: 50;
top: 50;
translate: -50% -50%;
z-index: 900;
}


This uses manages the size of the mouse follower and gives it a nice circular shape and attention seeking border. The position fixed is the most important otherwise the element will not be able to follow the mouse properly.


JS:

const shape = document.querySelector(".mouse-follower");

document.body.onpointermove = (event) => {
let { clientX, clientY } = event;
shape.animate(
{
left: `${clientX}px`,
top: `${clientY}px`,
},
{ duration: 2000, fill: "forwards" }
);
};

Here we basically select the follower element and listen for the pointer move event. This pointer event is then passed in the left and top style of the element through the animate() method, which gives the element a slight lag animation.  

That's it. Now you have a playful little mouse follower which adds to the interactivity of your website.

Comments

Popular Posts