RGB Color Guessing Game in JavaScript | Coodeverse
RGB Color Guessing Game — Free Vanilla JavaScript Project with Easy Mode (3 Squares) and Hard Mode (6 Squares), DOM Manipulation, Math.random(), classList, and CSS Grid
The RGB color guessing game is one of the most beloved beginner JavaScript projects ever created — taught in bootcamps, university courses, and YouTube tutorials worldwide for over a decade. Its genius lies in how naturally it teaches the most foundational JavaScript DOM skills while being genuinely fun to play. Unlike to-do lists or weather apps (which feel like homework), the color guessing game feels like an actual game. Players get emotionally invested — they want to win, they feel the satisfaction of a correct guess, and they feel the tension of Hard mode's 6-square challenge. This engagement makes it memorable as a learning experience and highly shareable as a portfolio piece.
The project teaches nine DOM skills in one compact, complete application. document.createElement() and container.appendChild() — the dynamic element creation pattern that is the conceptual foundation of every UI framework's rendering system. addEventListener() with click events — the event-driven programming model that governs all interactive web applications. Math.floor(Math.random() * 256) — the random integer generation pattern used in games, randomized UI, A/B testing, and cryptographic key generation. classList.add() and classList.remove() — the CSS class toggle pattern used for tabs, modals, dropdowns, themes, and every stateful UI component. element.style.backgroundColor — direct inline style manipulation for dynamic color application. String comparison for state checking — the foundational logic pattern for matching, filtering, and validation. querySelectorAll() with forEach() — batch DOM operations used in animations, form validation, and bulk updates. textContent assignment — updating displayed text in response to user actions. innerHTML = '' — clearing a container to re-render fresh content. All nine in one small, deployable, playable game.
The CSS architecture is equally instructive. CSS Grid with grid-template-columns: repeat(3, 1fr) creates the responsive color grid — the 1fr unit and auto row creation are the two Grid concepts developers use most. The padding-bottom: 100% aspect ratio trick for perfectly square elements works at any viewport width. CSS transitions (transition: background 0.6s) on the squares produce the smooth color-change animation when an incorrect guess eliminates a square or a correct guess reveals the answer. The responsive mobile breakpoint at max-width: 600px switches the grid to repeat(2, 1fr) — the correct approach to a two-column mobile layout for 6-square hard mode.
This project is a fixture of the web development bootcamp curriculum because it was famously featured in Colt Steele's Web Developer Bootcamp — one of the most popular programming courses ever created with over 900,000 students. Building your own version of this game demonstrates that you have completed equivalent foundational JavaScript training and can produce working, interactive browser applications from scratch.
Frequently Asked Questions — RGB Color Guessing Game
Why is the RGB color guessing game a classic JavaScript beginner project?
The RGB color guessing game became a classic JavaScript beginner project because it uniquely satisfies four requirements that most tutorials fail to address simultaneously. First, it is genuinely playable — it functions as a real game with clear win/lose states, difficulty levels, and replayability. This means developers actually use their own project after building it, reinforcing their understanding through play. Second, it is visually satisfying — the color reveal animation, the header color change on win, and the disappearing wrong squares are all visually rewarding feedback loops. Third, it covers the complete fundamental JavaScript toolkit in one project — DOM selection, dynamic element creation, event listeners, random number generation, array manipulation, string comparison, class toggling, and inline style manipulation. Most tutorials cover these in isolation; this project combines them in a natural, motivating context. Fourth, it has a clear, achievable scope for a beginner — the entire project is under 100 lines of JavaScript, no external libraries, no backend, no complex state management. It produces a polished, shareable result without overwhelming complexity. These qualities made it the signature project of Colt Steele's Web Developer Bootcamp and have kept it relevant as a learning tool for over a decade despite the JavaScript ecosystem changing dramatically around it.
How do you add a score counter to the RGB color guessing game?
Adding a score counter to the RGB color guessing game requires three additions. HTML: add a score display element in the stripe bar: span id='score'>Score: 0 is incremented on each correct guess. JavaScript variable: let score = 0 at the top of the script alongside numSquares. In the correct guess branch of the click listener, add score++ then update: document.getElementById('score').textContent = 'Score: ' + score. In the reset() function, add score = 0 and update the display to reset between games. For a persistent high score using localStorage: const bestScore = localStorage.getItem('rgbBestScore') || 0; on page load. After score++, check if (score > bestScore) { localStorage.setItem('rgbBestScore', score); } and display the best score in a separate element. This extension teaches two new skills beyond the base game: mutable state variables (score as state that changes in response to events) and localStorage for persisting data across page reloads — the browser's simplest key-value storage API.
What is the difference between textContent and innerHTML in JavaScript?
textContent and innerHTML both read and write content inside an element, but in fundamentally different ways. textContent reads or sets the raw text content of an element and all its descendants. It does not parse HTML — any HTML tags in the string are treated as literal characters, not markup. element.textContent = 'Hello World' sets the text safely. element.textContent = 'Click me' would display 'Click me' as literal text, not a link. innerHTML reads or sets the HTML markup inside an element. It parses the string as HTML, creating real DOM elements. element.innerHTML = 'Click me' would create an actual clickable link. The critical difference for security: innerHTML with user-provided content is an XSS (Cross-Site Scripting) vulnerability. If a user's input contains script tags or event handlers, innerHTML will execute them. textContent is always safe because it never parses HTML. In the RGB game, textContent is used correctly for all text updates: messageDisplay.textContent = 'Correct!', resetButton.textContent = 'New Colors', colorDisplay.textContent = pickedColor.toUpperCase() — all plain text, no HTML needed. Use textContent for any text that comes from user input or dynamic data; reserve innerHTML for static, trusted HTML strings.
RGB Color Guessing Game — Complete Function Reference
The game is organized into six clearly separated functions. init() is the entry point — called once on page load, it calls setupModeButtons(), setupSquares(), and reset() in sequence to initialize the complete game state. setupModeButtons() attaches click event listeners to the Easy and Hard buttons, updating numSquares (3 or 6) and calling reset() to regenerate the game. setupSquares() dynamically creates numSquares div elements with the .square class, attaches a click handler to each, and appends them to the container — called on every mode switch to recreate the correct number of squares. reset() is the core state refresh function: generates a new colors array, picks a new pickedColor, updates the colorDisplay text, resets the header background to blue, resets the button text, clears the message, and applies the new colors to all squares. changeColors(color) iterates all squares with querySelectorAll and forEach, setting all backgrounds to the winning color — the satisfying visual "reveal" that shows what the correct color was. randomColor() generates a single random RGB color string — the most reusable single function in the project. pickColor() selects a random element from the colors array using Math.floor(Math.random() * colors.length) as an index. generateRandomColors(num) calls randomColor() num times and returns the array. Understanding this function separation is itself a learning outcome — modular, single-responsibility functions are the foundation of maintainable code.
How to Extend the RGB Game — 5 Upgrade Ideas
The base RGB game is intentionally simple to make it ideal for extensions. Five progressively advanced upgrades that each teach a new skill: (1) Score counter and high score with localStorage — adds state management and browser storage (covered in FAQ above). (2) Timer mode — add a countdown timer using setInterval() and clearInterval() that ends the round after 10 seconds, teaching interval-based JavaScript timing. (3) Animated number counter in the header — instead of instantly showing rgb(255, 87, 34), count each channel up from 0 using setInterval, teaching animation via JavaScript timing loops. (4) Color history display — show the last 5 winning colors as small swatches below the game using an array and splice(), teaching array state management and dynamic list rendering. (5) Gradient mode — instead of solid squares, generate CSS linear-gradient() backgrounds for each square and a gradient RGB display, teaching multi-value random generation and CSS gradient syntax. Each upgrade adds one new JavaScript concept without touching the existing game logic, making them safe to add incrementally without breaking the working base game.
Free RGB color guessing game — vanilla JavaScript DOM manipulation, Math.random(), classList, CSS Grid. Easy (3 squares) and Hard (6 squares) mode. Full HTML CSS JavaScript source code. Download free.
Pro Tip: Can you guess the correct RGB color from 6 squares? Hard mode is brutal — only true color masters survive! 🎨 Try the live preview below before downloading.
🆓 Free Forever📄 HTML + CSS + JS🎮 Playable Game🟢 Easy Mode (3 Squares)🔴 Hard Mode (6 Squares)🎲 Math.random()🖱️ DOM Manipulation🎨 CC BY 4.0
Full Source Code
HTML + CSS + JavaScript — three-tab project. The most complete DOM manipulation teaching project ever built. Covers 9 core JS DOM skills in one playable game: createElement, appendChild, addEventListener, Math.random(), classList.add/remove, style.backgroundColor, querySelectorAll forEach, textContent, innerHTML reset. Study the JS tab in order — each function teaches a distinct concept. The most valuable 80 lines of JavaScript a beginner can read.