⚡ ZWRSK

🛠️ The Ultimate Guide to Building the 🎁 Secret Santa Drawer

Get ready for a deep dive! In this extremely descriptive tutorial, we tear down the exact JavaScript code and frameworks used to create our wildly popular 🎁 Secret Santa Drawer tool. Grab a coffee, and let's get coding!

🎥 Why Create Utilities for Streamers?

Building small, interactive utilities like this is not only a fantastic way to learn JavaScript, but they are also highly sought after by content creators! Streamers on Twitch and YouTube are always looking for engaging ways to interact with their chat. By building web-based tools that can be embedded in OBS, you create massive value.

We design our tools to be OBS-compatible so streamers can easily integrate them into their overlays. You can check out our dedicated Streamers Page to see how our tools are optimized for broadcasting! Making things interactive builds communities.

💻 Deep Dive: The JavaScript Engine

The 🎁 Secret Santa Drawer looks simple on the outside, but underneath the hood lies a robust, reactive state management system powered by vanilla JavaScript. Let's break down the code to understand exactly how it works.

Section 1: Initial State & Properties


            return {
                mode: 'live', // 'live' or 'instant'
                soundEnabled: true,
                namesInput: 'Sanne, Daan, Alex, Emma, Lucas',
                namesList: [],
                secretMap: {},
                turnOrder: [],
                currentTurnIndex: 0,
                // Spin state
                isSpinning: false,
                spinText: 'Spin the wheel!',
                phase: 'setup', // 'setup', 'idle', 'spin', 'wrapped', 'unwrapped', 'finished'
                isUnwrapped: false,

The Breakdown:

This section initializes the Alpine.js reactive state. Everything defined here becomes automatically available in the HTML. By setting sensible default values, we prevent the UI from loading in a broken or empty state.

Section 2: Application Logic Part 1

                audioCtx: null,
                get currentPerson() {
                    return this.turnOrder[this.currentTurnIndex] || '';
                },
                get drawnPerson() {
                    return this.secretMap[this.currentPerson] || '';
                },
                get nextPerson() {
                    return this.turnOrder[this.currentTurnIndex + 1] || '';
                },
                // Derangement generator (no self-picks)
                generateDerangement(arr) {
                    let n = arr.length;
                    let result = [...arr];
                    let isValid = false;

The Breakdown:

  • This part handles the Web Audio API or HTML5 Audio elements, allowing us to play ticking sounds or victory fanfares to gamify the experience.
  • This relies on JavaScript's getter syntax (get), which acts as a computed property in Alpine.js. Whenever a dependency inside it changes, it automatically recalculates without needing manual event listeners.

Section 3: Application Logic Part 2

                    while (!isValid) {
                        for (let i = n - 1; i > 0; i--) {
                            let j = Math.floor(Math.random() * (i + 1));
                            [result[i], result[j]] = [result[j], result[i]];
                        }
                        isValid = true;
                        for (let i = 0; i < n; i++) {
                            if (arr[i] === result[i]) {
                                isValid = false;
                                break;
                            }
                        }
                    }

The Breakdown:

  • We utilize Math.random() here to introduce randomization. This is the core engine of the game's unpredictability, allowing us to shuffle arrays or pick random elements.

Section 4: Application Logic Part 3

                    let map = {};
                    for (let i = 0; i < n; i++) {
                        map[arr[i]] = result[i];
                    }
                    return map;
                },
                startLiveShow() {
                    let raw = this.namesInput.split(',').map(s => s.trim()).filter(s => s);
                    if (raw.length < 3) {
                        alert('Please enter at least 3 names!');
                        return;
                    }
                    this.namesList = raw;
                    this.turnOrder = [...raw].sort(() => Math.random() - 0.5);
                    this.secretMap = this.generateDerangement(raw);
                    this.currentTurnIndex = 0;
                    this.phase = 'idle';
                    this.isUnwrapped = false;
                },

The Breakdown:

  • We utilize Math.random() here to introduce randomization. This is the core engine of the game's unpredictability, allowing us to shuffle arrays or pick random elements.
  • Here, we process the raw string input from the user. Using chained array methods like .split(), .map(), and .filter() cleans up whitespace and removes empty entries effortlessly.

Section 5: Application Logic Part 4

                playTickSound(pitch = 500) {
                    if (!this.soundEnabled) return;
                    try {
                        if (!this.audioCtx) {
                            this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                        }
                        if (this.audioCtx.state === 'suspended') this.audioCtx.resume();
                        const osc = this.audioCtx.createOscillator();
                        const gain = this.audioCtx.createGain();
                        osc.type = 'triangle';
                        osc.frequency.setValueAtTime(pitch, this.audioCtx.currentTime);
                        gain.gain.setValueAtTime(0.1, this.audioCtx.currentTime);
                        gain.gain.exponentialRampToValueAtTime(0.001, this.audioCtx.currentTime + 0.04);
                        osc.connect(gain);
                        gain.connect(this.audioCtx.destination);
                        osc.start();
                        osc.stop(this.audioCtx.currentTime + 0.04);
                    } catch (e) {}
                },

The Breakdown:

  • This part handles the Web Audio API or HTML5 Audio elements, allowing us to play ticking sounds or victory fanfares to gamify the experience.

Section 6: Application Logic Part 5

                playGiftUnwrapSound() {
                    if (!this.soundEnabled) return;
                    try {
                        if (!this.audioCtx) return;
                        const notes = [523.25, 659.25, 783.99, 1046.50];
                        notes.forEach((freq, i) => {
                            setTimeout(() => {
                                try {
                                    const osc = this.audioCtx.createOscillator();
                                    const gain = this.audioCtx.createGain();
                                    osc.type = 'sine';
                                    osc.frequency.value = freq;
                                    gain.gain.setValueAtTime(0.15, this.audioCtx.currentTime);
                                    gain.gain.exponentialRampToValueAtTime(0.001, this.audioCtx.currentTime + 0.25);
                                    osc.connect(gain);
                                    gain.connect(this.audioCtx.destination);
                                    osc.start();
                                    osc.stop(this.audioCtx.currentTime + 0.25);
                                } catch (e) {}
                            }, i * 80);
                        });
                    } catch (e) {}
                },

The Breakdown:

  • Notice the use of setTimeout. While JavaScript can calculate results instantly, adding a slight artificial delay creates suspense and makes the application feel like a physical game.
  • This part handles the Web Audio API or HTML5 Audio elements, allowing us to play ticking sounds or victory fanfares to gamify the experience.

Section 7: Application Logic Part 6

                spinRoulette() {
                    if (this.isSpinning) return;
                    this.isSpinning = true;
                    this.phase = 'spin';
                    this.isUnwrapped = false;
                    let possibleTargets = this.namesList.filter(n => n !== this.currentPerson);
                    let delays = [50, 50, 50, 50, 50, 60, 80, 110, 150, 220, 320, 480, 650];
                    let step = 0;
                    const runSpin = () => {
                        if (step < delays.length) {
                            let randName = possibleTargets[Math.floor(Math.random() * possibleTargets.length)];
                            this.spinText = randName;
                            this.playTickSound(400 + step * 15);
                            let currentDelay = delays[step];
                            step++;
                            setTimeout(runSpin, currentDelay);
                        } else {
                            this.isSpinning = false;
                            this.phase = 'wrapped';
                        }
                    };

The Breakdown:

  • We utilize Math.random() here to introduce randomization. This is the core engine of the game's unpredictability, allowing us to shuffle arrays or pick random elements.
  • Notice the use of setTimeout. While JavaScript can calculate results instantly, adding a slight artificial delay creates suspense and makes the application feel like a physical game.
  • Here, we process the raw string input from the user. Using chained array methods like .split(), .map(), and .filter() cleans up whitespace and removes empty entries effortlessly.

Section 8: Application Logic Part 7

                    runSpin();
                },
                unwrapGift() {
                    if (this.phase !== 'wrapped') return;
                    this.isUnwrapped = true;
                    this.phase = 'unwrapped';
                    this.playGiftUnwrapSound();
                },
                nextTurn() {
                    if (this.currentTurnIndex < this.turnOrder.length - 1) {
                        this.currentTurnIndex++;
                        this.phase = 'idle';
                        this.isUnwrapped = false;
                    } else {
                        this.phase = 'finished';
                    }
                },

The Breakdown:

  • This function handles specific business logic for the tool. It mutates the state (variables on `this`), which Alpine.js immediately detects, causing the HTML UI to re-render the changes instantly.

Section 9: Application Logic Part 8

                // Instant list mode logic
                instantPairs: [],
                drawInstant() {
                    let raw = this.namesInput.split(',').map(s => s.trim()).filter(s => s);
                    if (raw.length < 3) {
                        alert('Please enter at least 3 names!');
                        return;
                    }
                    let map = this.generateDerangement(raw);
                    this.instantPairs = Object.keys(map).map(giver => `${giver} ➔ ${map[giver]}`);
                }
            }
        }

The Breakdown:

  • Here, we process the raw string input from the user. Using chained array methods like .split(), .map(), and .filter() cleans up whitespace and removes empty entries effortlessly.

🌐 Frameworks Used & How to Link Them

Building modern web apps doesn't always require massive build tools like Webpack or Vite. For standalone utilities like ours, injecting powerful frameworks directly into the HTML via CDN (Content Delivery Network) is the fastest way to get started.

Alpine.js

Alpine is a rugged, minimal tool for composing behavior directly in your markup. It gives you the reactive and declarative nature of big frameworks like Vue or React at a fraction of the cost.

🔗 External Link: Official Alpine.js Website

How to link in HTML:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

Place this inside your <head> tag. The defer attribute ensures it loads without blocking your HTML rendering.

🎨

Tailwind CSS

Tailwind is a utility-first CSS framework packed with classes like flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup.

🔗 External Link: Official Tailwind CSS Website

How to link in HTML (via CDN for prototyping):

<script src="https://cdn.tailwindcss.com"></script>

Place this in your <head> tag. While great for development and small utilities, for large production sites, you should install Tailwind via Node to purge unused CSS.

📚 Suggested Educational Resources

Want to learn more about the JavaScript concepts and frameworks used in this code? Check out these excellent free resources to level up your coding skills!

❓ FAQ about the Code

Is it hard to learn Alpine.js if I only know Vanilla JS?

Not at all! Alpine is designed to map directly to standard JavaScript. If you understand how a basic JS object and function work, you can pick up Alpine.js in literally one afternoon.

Why not use a database?

To ensure absolute privacy and lightning-fast speed, everything runs client-side in the browser. A database would add unnecessary overhead for these utility tools.

Can I copy this code for my own site?

Yes! We encourage you to build your own versions. Inspect the source code, see how the `x-data` object is structured, and try making modifications.

⬅️ Previous: Who's Most Likely To... Back to Utility Tool Next: Virtual Fine Jar ➡️