⚡ ZWRSK

🛠️ The Ultimate Guide to Building the 🫙 Virtual Fine Jar

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 🫙 Virtual Fine Jar 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 🫙 Virtual Fine Jar 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 {
                soundEnabled: true,
                jarTotal: 0.00,
                offenders: [
                    { name: 'Alex 😈', total: 3.50 },
                    { name: 'Sophie ☕', total: 1.50 },
                    { name: 'Daan ⏰', total: 2.00 }
                ],
                newOffenderName: '',
                selectedOffender: 'Alex 😈',

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

                // Wheel Gamble State
                isSpinning: false,
                rouletteResult: '',
                phase: 'idle', // 'idle', 'spinning', 'result'
                audioCtx: null,
                fines: [
                    { id: 'swear', label_en: '🤬 Swearing / Foul Mouth', label_nl: '🤬 Vloeken / Schelden', cost: 0.50 },
                    { id: 'late', label_en: '⏰ Late to Meeting', label_nl: '⏰ Te Laat Komen', cost: 1.00 },
                    { id: 'phone', label_en: '📱 Phone Ringtone Busted', label_nl: '📱 Telefoon Niet Op Stil', cost: 1.50 },
                    { id: 'coffee', label_en: '☕ Forgot Coffee Duty', label_nl: '☕ Geen Koffie Gezet', cost: 2.00 },
                    { id: 'cringe', label_en: '💩 Terrible Joke Cringe Tax', label_nl: '💩 Tenenkrommende Grap', cost: 0.50 }
                ],

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 3: Application Logic Part 2

                punishments_en: [
                    { text: "😇 PARDON! €0.00 FINE!", cost: 0, color: "bg-emerald-400 text-black" },
                    { text: "💸 PAY STANDARD FINE (€1.00)", cost: 1.0, color: "bg-yellow-300 text-black" },
                    { text: "💥 DOUBLE FINE! (€2.00)", cost: 2.0, color: "bg-rose-500 text-white" },
                    { text: "🍻 BUY NEXT ROUND OF DRINKS!", cost: 2.5, color: "bg-amber-400 text-black" },
                    { text: "💃 DO 10 JUMPING JACKS NOW!", cost: 1.0, color: "bg-cyan-400 text-black" },
                    { text: "🔥 TRIPLE PENALTY! (€3.00)", cost: 3.0, color: "bg-purple-600 text-white" }
                ],
                punishments_nl: [
                    { text: "😇 GRATIS KWIJTGESCHELD! €0.00", cost: 0, color: "bg-emerald-400 text-black" },
                    { text: "💸 BETAAL NORMALE BOETE (€1.00)", cost: 1.0, color: "bg-yellow-300 text-black" },
                    { text: "💥 DUBBELE BOETE! (€2.00)", cost: 2.0, color: "bg-rose-500 text-white" },
                    { text: "🍻 HET VOLGENDE RONDJE HALEN!", cost: 2.5, color: "bg-amber-400 text-black" },
                    { text: "💃 10 JUMPING JACKS DOEN!", cost: 1.0, color: "bg-cyan-400 text-black" },
                    { text: "🔥 DRIEDUBBELE BOETE! (€3.00)", cost: 3.0, color: "bg-purple-600 text-white" }
                ],

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 4: Application Logic Part 3

                get jarFillPercentage() {
                    let max = 50; // max jar capacity
                    let p = Math.min(100, Math.round((this.jarTotal / max) * 100));
                    return p;
                },
                get topOffender() {
                    if (!this.offenders.length) return null;
                    return [...this.offenders].sort((a, b) => b.total - a.total)[0];
                },
                addOffender() {
                    if (!this.newOffenderName.trim()) return;
                    let name = this.newOffenderName.trim();
                    this.offenders.push({ name: name, total: 0.00 });
                    this.selectedOffender = name;
                    this.newOffenderName = '';
                },

The Breakdown:

  • 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 5: Application Logic Part 4

                addFine(cost) {
                    this.jarTotal += cost;
                    let target = this.offenders.find(o => o.name === this.selectedOffender);
                    if (target) {
                        target.total += cost;
                    }
                    this.playCoinDropSound();
                },
                playCoinDropSound() {
                    if (!this.soundEnabled) return;
                    try {
                        if (!this.audioCtx) {
                            this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                        }
                        if (this.audioCtx.state === 'suspended') this.audioCtx.resume();

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 6: Application Logic Part 5

                        const osc = this.audioCtx.createOscillator();
                        const gain = this.audioCtx.createGain();
                        osc.type = 'sine';
                        osc.frequency.setValueAtTime(1200, this.audioCtx.currentTime);
                        osc.frequency.exponentialRampToValueAtTime(300, this.audioCtx.currentTime + 0.12);
                        gain.gain.setValueAtTime(0.2, this.audioCtx.currentTime);
                        gain.gain.exponentialRampToValueAtTime(0.001, this.audioCtx.currentTime + 0.12);
                        osc.connect(gain);
                        gain.connect(this.audioCtx.destination);
                        osc.start();
                        osc.stop(this.audioCtx.currentTime + 0.12);
                    } 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 7: Application Logic Part 6

                playFanfareSound() {
                    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 = 'triangle';
                                    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 8: Application Logic Part 7

                spinGambleWheel() {
                    if (this.isSpinning) return;
                    this.isSpinning = true;
                    this.phase = 'spinning';
                    let isNl = (document.documentElement && document.documentElement.getAttribute('lang')) === 'nl';
                    let list = isNl ? this.punishments_nl : this.punishments_en;
                    let delays = [50, 50, 50, 50, 60, 80, 110, 150, 220, 320, 480, 650];
                    let step = 0;
                    let finalOutcome = list[Math.floor(Math.random() * list.length)];
                    const runSpin = () => {
                        if (step < delays.length) {
                            let rand = list[Math.floor(Math.random() * list.length)];
                            this.rouletteResult = rand;
                            this.playCoinDropSound();
                            let currentDelay = delays[step];
                            step++;
                            setTimeout(runSpin, currentDelay);
                        } else {
                            this.rouletteResult = finalOutcome;
                            this.isSpinning = false;
                            this.phase = 'result';
                            if (finalOutcome.cost > 0) {
                                this.addFine(finalOutcome.cost);
                            }
                            this.playFanfareSound();
                        }
                    };

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.

Section 9: Application Logic Part 8

                    runSpin();
                },
                resetJar() {
                    if (confirm('Reset all fines in jar to €0.00?')) {
                        this.jarTotal = 0.00;
                        this.offenders.forEach(o => o.total = 0.00);
                    }
                }
            }
        }

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.

🌐 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: Secret Santa Drawer Back to Utility Tool Next: Who Pays The Bill ➡️