JSFiddle - React, Tailwind, and code Playground

by Jordan Sayner

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/confetti.browser.min.js"></script>
    <h1>Scroll to the bottom to see the confetti!</h1>

    <div id="target">🎉 Target Element 🎉</div>

CSS

body {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        #target {
            margin-top: 1500px; /* Position the target element towards the bottom */
            width: 100%;
            height: 200px;
            background-color: lightblue;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
        }

JavaScript

// Function to trigger confetti
        function triggerConfetti() {
            confetti({
                particleCount: 100,
                spread: 70,
                origin: { y: 0.5 } // Adjust origin if needed
            });
        }

        // Set up the IntersectionObserver
        const targetElement = document.getElementById('target');
        const observer = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // Trigger confetti when the target element is in view
                    triggerConfetti();
                    // Optionally, disconnect the observer after the first trigger
                    //observer.disconnect();
                }
            });
        }, { threshold: 0.5 }); // Trigger when 50% of the element is visible

        // Start observing the target element
        observer.observe(targetElement);