Tutorials

avatar

Malik Kotb

Feb 26, 2024 / Beginner / Short

Flashlight Gradient
Flashlight Hover Effect with Next.js and CSS

Create a smooth flashlight hover mouse effect with a gradient using Next.js (JavaScript) and CSS.

Initializing the project

Quick one today.

Let's start the project by setting up a Next.js app with TypeScript and utilizing the app router. Just run npx create-next-app@latest in the terminal.

We can clear out all the contents in the page.tsx, and global.css files, and add our own HTML and CSS, to begin with a clean slate in the application.

CSS Module

Where the magic happens...

This CSS code creates a radial gradient background image with customizable position and color.

page.tsx

1.cover {
2    background-image: radial-gradient(
3      circle farthest-side at var(--x, 100px) var(--y, 100px),
4      var(--color, #1250aa) 0%,
5      transparent 100%
6    );
7  }
8

Page Component

We will start by creating a function that generates a hex code for a random color.

page.tsx

1function getRandomHexCode() {
2  return "#" + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0");
3}
4

Then we can set the random color when hovering over the text. We will call setColor using onMouseEnter and onMouseLeave handlers of the text.

page.tsx

1const setColor = () => {
2    if (!coverRef.current) return;
3    const randomColor = getRandomHexCode();
4    coverRef.current.style.setProperty("--color", `${randomColor}`);
5  };
6

Now we need a way of tracking the position of our mouse. We can do that by adding an event-listener to our window.

page.tsx

1  const manageMouseMove = (e: { clientX: any; clientY: any }) => {
2    if (!coverRef.current) return;
3    const { clientX, clientY } = e;
4    coverRef.current.style.setProperty("--x", `${clientX}px`);
5    coverRef.current.style.setProperty("--y", `${clientY}px`);
6  };
7
8  useEffect(() => {
9    window.addEventListener("mousemove", manageMouseMove);
10    return () => {
11      window.removeEventListener("mousemove", manageMouseMove);
12    };
13  }, []);
14
We should have something like this:
Wrapping up.

Quick and smooth, right?

Hope you liked the animation and learned something new!

-Malik

Things for creative devs
sent to your inbox every week