dhairyashah
Portfolio

Jun 16th, 2023

How to create a confetti effect in HTML?

Author Picture

Dhairya Shah

Software Engineer

Adding a confetti effect to a website can bring an element of celebration and joy to various interactions. This article will explore how to create a confetti effect in HTML using the famous library, Canvas Confetti, which allows you to generate colorful and animated confetti particles on a web page.

There are lots of ways you can add confetti to your website. But, in this article, I will share a super simple method to add it to your website.

Setting up HTML

Inside your HTML file, we need to link a javascript file to it.

<script type="module" src="confetti.js"></script>

Note: Please ensure that you include type="module" in the script tag; otherwise, the JavaScript code may not function as intended.

<button id="btn">Click me</button>

I have created a button to pop confetti upon clicking the button.

Creating confetti

We’ll be using Canvas Confetti using Skypack.

Inside your javascript file, add the following code to import the required package to our webpage.

import confetti from 'https://cdn.skypack.dev/canvas-confetti';

Once finished importing, create a function to initialize the confetti from the imported package,

function makeConfetti(){
    confetti()
}

Now after creating the function we’ll call it,

const btn = document.getElementById("btn")
btn.addEventListener("click", makeConfetti)
Tada! You have successfully popped confetti in HTML in just two lines of code. (Click here to pop confetti)

Source code: https://github.com/dhairyathedev/confetti-tutorial

I hope you have learned something new from this article. Thanks a lot for reading till the end, have a great day!

Cover Photo by Damiano Lingauri on Unsplash