DEV Community

Cover image for How to create a confetti effect in HTML?
Dhairya Shah
Dhairya Shah

Posted on Originally published at dhairyashah.dev

How to create a confetti effect in HTML?

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>
🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini 🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini

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>
🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini 🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini

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';
🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini 🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini

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

function makeConfetti(){
    confetti()
}
🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini 🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini

Now after creating the function we’ll call it,

const btn = document.getElementById("btn")
btn.addEventListener("click", makeConfetti)
🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini 🔴 Live TV: dhairyashah/how to create a confetti effect in html m - Pertandingan Hari Ini

Tada! You have successfully popped confetti in HTML in just two lines of code.

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!

Credits: Banner Image - Photo by Damiano Lingauri on Unsplash

Top comments (0)