Tutorials
Malik Kotb
Feb 26, 2024 / Beginner / Short
Create a smooth flashlight hover mouse effect with a gradient using Next.js (JavaScript) and CSS.
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.
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
radial-gradient
. The gradient starts from a circle shape and extends to the farthest-side
of its container (the window).--x
and --y
, defaulting to (100px, 100px) which is in the top left corner of the window.--color
, defaulting to #1250aa.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
clientX
and clientY
properties of the event.