How to make a confetti burst on click
A no-library tutorial for a small burst of colorful confetti that pops out from the exact spot where someone clicks a link or button.

A little confetti on click is a fun way to say thanks, mark a finished task or celebrate a signup. In this tutorial you'll build a small burst that pops out from the exact spot someone clicks, then drifts down and fades away. It uses plain HTML, a few lines of CSS and the Web Animations API, with no library. You'll also make sure links still go where they should, keyboard users get the burst too, and people who prefer less motion don't get it at all.
The idea
The whole effect is simple. When a click happens, you grab its position, create a few dozen tiny colored rectangles right there, and send each one off in a random direction. Every piece spins a bit, falls a little, fades out and then gets removed from the page.
You could draw the pieces on a canvas, but plain span elements are easier to follow and easy to style. Each piece is fixed to the viewport, so it lines up with the click coordinates no matter how far down the page you've scrolled. pointer-events: none means the pieces never block a click.
<a href="/thanks" class="confetti-link">Say thanks</a>
<button type="button" class="confetti-button">Celebrate</button>
<style>
.confetti-piece {
position: fixed;
left: 0;
top: 0;
width: 8px;
height: 5px;
border-radius: 1px;
pointer-events: none;
z-index: 1000;
}
</style>Making and scattering the pieces
The burst function takes an x and y position and loops PIECE_COUNT times. For each piece it picks a random color, a random angle all the way around the circle, and a random distance. A bit of trigonometry turns the angle and distance into a sideways and up or down offset.
element.animate() does the moving. The first keyframe puts the piece on the click point. By 60% of the way through it has flown out and spun. The last keyframe drops it another 60px and fades it to nothing, which reads as a gentle fall. Random durations keep the pieces from landing all at once.
const CONFETTI_COLORS = ['#ff5fa2', '#9b5de5', '#3a86ff', '#ffd23f', '#2ec4b6'];
const PIECE_COUNT = 40;
function burst(x, y) {
for (let i = 0; i < PIECE_COUNT; i++) {
const piece = document.createElement('span');
piece.className = 'confetti-piece';
piece.style.background =
CONFETTI_COLORS[Math.floor(Math.random() * CONFETTI_COLORS.length)];
document.body.appendChild(piece);
const angle = Math.random() * Math.PI * 2;
const distance = 40 + Math.random() * 80;
const dx = Math.cos(angle) * distance;
const dy = Math.sin(angle) * distance;
const spin = (Math.random() - 0.5) * 720;
const animation = piece.animate(
[
{ transform: `translate(${x}px, ${y}px) rotate(0deg)`, opacity: 1 },
{
transform: `translate(${x + dx}px, ${y + dy}px) rotate(${spin}deg)`,
opacity: 1,
offset: 0.6,
},
{
transform: `translate(${x + dx}px, ${y + dy + 60}px) rotate(${spin * 1.5}deg)`,
opacity: 0,
},
],
{
duration: 700 + Math.random() * 300,
easing: 'ease-out',
fill: 'forwards',
}
);
animation.onfinish = () => piece.remove();
}
}Cleaning up when the pieces land
Forty spans per click adds up fast if nobody tidies. That's what the onfinish line in the code above is for: when a piece's animation ends, it removes itself from the page.
fill: 'forwards' keeps each piece at its last keyframe, fully transparent, until it's removed. Without it, a piece would snap back to the top left corner for a split second before the cleanup runs.
Working out where the click came from
Mouse and touch clicks come with clientX and clientY, which are exactly the viewport coordinates the fixed pieces need. Keyboard clicks are different. Pressing Enter on a link or button still fires a click event, but there's no pointer, so those coordinates are no help.
The easy tell is event.detail. For a real click it's the click count, 1 or more. For a click triggered from the keyboard it's 0. In that case, use the center of the element instead, so the burst comes from the button itself.
function getOrigin(event) {
// A click from the keyboard (Enter on a link, Enter or Space on a button) has detail 0
// and no useful pointer position, so use the element's center.
if (event.detail === 0) {
const rect = event.currentTarget.getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
}
return { x: event.clientX, y: event.clientY };
}Skipping the burst for reduced motion
Some people turn on a reduced motion setting in their system because moving things make them feel unwell. Flying confetti is exactly the kind of extra motion they asked to skip, so check the prefers-reduced-motion media query first and return early if it matches.
Buttons that do something on the same page are the simplest case. There's no navigation to worry about, so the handler checks the setting, finds the origin and fires the burst.
function prefersReducedMotion() {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}
document.querySelectorAll('.confetti-button').forEach((button) => {
button.addEventListener('click', (event) => {
if (prefersReducedMotion()) return;
const { x, y } = getOrigin(event);
burst(x, y);
});
});Letting the link still go somewhere
Links are trickier. A normal click loads the next page right away, and the confetti vanishes with the old one before anyone sees it. The fix is to cancel the default navigation, wait about 300ms, then go to the link's href yourself.
Only do that when the page is actually leaving. If the link opens in a new tab, or someone holds Cmd, Ctrl or Shift to open it elsewhere, let the browser handle it normally. And with reduced motion on, there's no burst, so there's no reason to make anyone wait.
document.querySelectorAll('.confetti-link').forEach((link) => {
link.addEventListener('click', (event) => {
if (prefersReducedMotion()) return;
const { x, y } = getOrigin(event);
burst(x, y);
// New tab or modified click: the page stays open, so no need to wait.
const opensElsewhere =
link.target === '_blank' ||
event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
if (opensElsewhere) return;
// Same tab: hold the navigation just long enough to see the pop.
event.preventDefault();
setTimeout(() => {
window.location.href = link.href;
}, 300);
});
});Want a bigger or smaller party? PIECE_COUNT and the distance range are the two numbers to play with. Links that open in a new tab already skip the delay, since the current page stays put and every piece gets to finish its fall.
More articles

How to make a headline type itself out
Build a headline that types itself out letter by letter with a blinking cursor, using plain HTML, CSS and a few lines of JavaScript.

How to add a copy button to code blocks
Add a small Copy button to every code block on your page that copies the code, says Copied for a moment, and tells screen reader users what happened.

How to add a reading progress bar
Build a thin pink bar that fills across the top of the screen as someone reads your article, with a small JavaScript version and a pure CSS version for browsers that support scroll-driven animations.

How to build a dark mode toggle
A step-by-step tutorial for a dark mode that follows your visitor's device setting, adds a toggle button that saves their pick in localStorage, and never flashes the wrong theme on load.

How to make a glowing border spin
A pure CSS tutorial for a card with a pink, purple and blue gradient border that spins around the edge and glows softly, with a calm static version for people who prefer less motion.

How to make cards lift as you scroll on a phone
Phones can't hover, so our blog cards used to sit flat on mobile. Here's the small CSS class and IntersectionObserver we use to lift whichever card is in the middle of the screen as you scroll.

How to build a thought-bubble tooltip with pure CSS
A step-by-step CSS tutorial for a tooltip that reads its label from a data attribute, pops up in a rounded bubble, trails off in three little circles and stays clickable, with no JavaScript.

What is Hermes?
Hermes is an open source AI agent harness from Nous Research that runs on your own computer, uses tools, remembers past sessions and learns skills. Here is what it does and how to install and set it up.

Meet the Night Sky UI Kit
Three animated React components for dark, night-sky themed sites: a star cursor, a twinkling starfield and a soft aurora glow. Here is what's inside and how to add it.

Behind the Star Cursor
How the Star Cursor draws its comet tail and sparkle dust, and why it quietly steps aside on touch screens and for anyone who prefers reduced motion.

The moon is, in fact, an inanimate, dusty old rock
The moon is a layered ball of rock about 4.5 billion years old, wrapped in sharp gray dust and almost no air. Here is what it is made of, where it probably came from and why it barely changes.

How solar storms mess with satellites
The sun has weather, and some of it reaches us. Here is how solar flares and the storms that follow can sink satellites, scramble GPS and even trip power grids, and how people keep watch.

Patterns in sound
Sprinkle salt on a drum, play a steady note, and the grains slide into neat lines and rings. Here is why sound draws pictures, who first noticed, how to try it at home, and what all this has in common with a snowflake.

Most of the sound around you goes unheard
Human ears catch only a middle band of all the sound there is. Here is what we miss, which animals hear it, and why the hums and whines from our own gadgets can still get under our skin.

What is LaserSETI?
LaserSETI is a growing network of rooftop cameras that watch huge patches of the night sky for a single-color flash of light. Here is how it works, where the stations are in 2026, and what it has (and has not) found.

Most of the light around you is invisible
Our eyes catch only a thin band of all the light there is, from violet to red. Here is what we miss, which animals see more of it, and how we use the invisible rest every day.

The science of music
Why a good chorus gives you chills, why the Mozart effect fizzled, and why some songs refuse to leave your head. Here is what the research actually says about music, mood and focus.

Bill Nye is still teaching
A science show from the 1990s is still turning up in classrooms. Here is what Bill Nye the Science Guy was, why so many grownups remember it so fondly, and why teachers keep pressing play.

Why is the sky blue?
The sky is blue because the tiny bits of gas in the air reflect blue sunlight around much more than red light, so blue reaches our eyes from every part of the sky.

Why the sun and moon look the same size
The sun is about 400 times wider than the moon and also about 400 times farther away, so the two discs look almost the same size in our sky. That match is a coincidence of timing, and it will not last forever.

Bees fly more like drones than planes
A bumblebee stays in the air the way a drone or helicopter does, by moving its wings fast instead of racing forward over a stiff wing.

The earth is, in fact, actually round
You can check that Earth is round from a beach, a campsite or a phone call to a friend in another time zone. People worked it out more than two thousand years ago, and one of them even measured it with shadows.

5 trendy UI effects
A star cursor with a comet tail, frosted glass panels, scroll-driven animation, smooth page transitions and gradients that actually move, plus the one tip we would give for each.

What llms.txt is, and how we added one to our site
A plain-English look at llms.txt, the proposed markdown file that gives AI assistants a short map of your site, what it can and can't promise, and how we wrote and tested our own.

Tell Google who you are with a few lines of code
Small business names collide, and search engines have to guess which one you meant. Organization structured data is one way a site owner can stop them guessing. Here's what it is, what we put in ours, and how to test it.

Building night sky effects that know when to sit out
How the Night Sky UI Kit's star cursor, starfield and aurora check the visitor's device and settings before they draw a single frame.

How you can set up pull requests to get an automatic first review
Give every pull request an automatic first review the moment it opens, and send each new pull request and its review to a dedicated Slack channel. Here is how the pieces fit.

How visitors book a call on our site
Picking a time with us takes a few clicks and never leaves the page. Here is how the booking calendar on our site works, and the small checks that stop two people grabbing the same hour.

Inside our resumable, review-gated video production pipeline
How we built a local seven-step pipeline that turns a history topic into a captioned video, with resumable state, bounded retries, and a human review gate.