webdevpuneet.com

Password Generator — Free HTML CSS JS Snippet

Password Generator · Tools · Plain HTML, CSS & JS · Live preview

Copy & paste

Source Code

<div class="wrap">
  <div class="gen-card">
    <h2 class="gen-title">Password Generator</h2>
    <p class="gen-sub">Generate a strong, random password instantly.</p>

    <!-- Password output -->
    <div class="output-row">
      <div class="password-display" id="pw-display">Click Generate</div>
      <button class="copy-btn" id="copy-btn" onclick="copyPw()" title="Copy password" disabled>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
        <span id="copy-label">Copy</span>
      </button>
    </div>

    <!-- Strength meter -->
    <div class="strength-wrap" id="strength-wrap" style="display:none">
      <div class="strength-bar"><div class="strength-fill" id="strength-fill"></div></div>
      <span class="strength-label" id="strength-label"></span>
    </div>

    <!-- Settings -->
    <div class="settings">
      <div class="setting-row">
        <label class="setting-label">Length: <strong id="len-val">16</strong></label>
        <input type="range" class="len-range" id="len-range" min="8" max="32" value="16" oninput="updateLen(this.value)">
      </div>

      <div class="options-grid">
        <label class="opt"><input type="checkbox" id="opt-upper" checked onchange="regen()"> Uppercase A–Z</label>
        <label class="opt"><input type="checkbox" id="opt-lower" checked onchange="regen()"> Lowercase a–z</label>
        <label class="opt"><input type="checkbox" id="opt-num"   checked onchange="regen()"> Numbers 0–9</label>
        <label class="opt"><input type="checkbox" id="opt-sym"         onchange="regen()"> Symbols !@#$</label>
        <label class="opt"><input type="checkbox" id="opt-ambig"       onchange="regen()"> Exclude similar (0OIl)</label>
      </div>
    </div>

    <!-- Generate button -->
    <button class="gen-btn" onclick="generate()">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M4.5 9A8 8 0 0 1 19 8"/><path d="M19.5 15A8 8 0 0 1 5 16"/><path d="M19 5v4h-4"/><path d="M5 19v-4h4"/></svg>
      Generate password
    </button>

    <!-- History -->
    <div class="history-wrap" id="history-wrap" style="display:none">
      <div class="history-head">Recent <button class="clear-hist" onclick="clearHistory()">Clear</button></div>
      <ul class="history-list" id="history-list"></ul>
    </div>
  </div>
</div>

Extend with AI

Take This Snippet Further With AI

The AI prompt for this one is for Patreon supporters ($3 a month, 7 days free), along with a site with no ads. Supporters enter the passcode once and it is remembered in this browser.

· Become a supporter

What's included

Features

crypto.getRandomValues() — cryptographically secure entropy, not Math.random()
6-point strength scoring: length tiers + charset presence checks
Exclude similar: Set of ambiguous chars (0OIlB8), filtered from charset
Length slider 8-32: auto-regenerates on change if a password exists
5-item history: unshift newest, cap at 5, individual copy buttons per item
Copy button: Clipboard API + .copied green state + 2s reset
Strength bar: width+background+label update atomically on each generate
Options checkboxes: auto-regen via onchange="regen()" if password exists

About this UI Snippet

Password Generator — Cryptographic Randomness, Strength Meter, Options & Copy History

Screenshot of the Password Generator snippet rendered live

Ask a hundred people to "type a random password" and you'll get a hundred passwords shaped by human habit — favourite numbers, keyboard patterns, a capital letter only at the start. Computers are much better at *actually* random, which is the entire reason password generators exist: they remove the human from the one step where humans are predictably bad. This snippet builds a complete one — cryptographically secure generation, an 8–32 character length slider, checkboxes for each character class plus an "exclude look-alike characters" option, a live strength meter, one-click clipboard copy, and a five-item history so a regenerated password isn't lost forever.

Why crypto.getRandomValues() and not Math.random()

This is the one decision in the whole snippet that actually matters for security, so it's worth understanding precisely *why*. Math.random() is a pseudo-random number generator — deterministic math seeded from an internal state, which means that given enough observed outputs, an attacker can reconstruct the seed and predict every value that comes next. That's a frightening property for something protecting an account. crypto.getRandomValues(new Uint32Array(length)) instead draws from the operating system's entropy pool — noise gathered from hardware events like disk timing and interrupt jitter — producing numbers that are genuinely unpredictable, not just statistically scattered. Each 32-bit integer is then mapped onto the chosen character set with charset[n % charset.length], a modulo operation that wraps a huge number down into a small alphabet while preserving its randomness.

Scoring strength as a sum of small truths

Rather than a single opaque "strength score," the meter adds up six independent yes/no checks — is it at least 12 characters? At least 16? Does it contain an uppercase letter, a lowercase letter, a digit, a symbol? Each "yes" contributes one point out of six, the total becomes a percentage, and that percentage drives both the fill width and colour of .strength-fill through four bands: Weak (red), Fair (amber), Good (green), Strong (indigo). Building the meter from named, inspectable conditions rather than a black-box formula means anyone reading the code — or extending it — can see *exactly* what separates a "Fair" password from a "Strong" one, the same transparency the Password Strength Meter snippet applies to user-typed input.

A Set that filters out the characters people mistype

The digits 0 and 1, the letters O, I, and l, and a handful of others look nearly identical in many fonts — exactly the characters someone squints at when copying a password by hand onto a sticky note or a phone keyboard. The "Exclude similar" option collects them into a Set (for constant-time .has() lookups) and, when checked, filters the active character set with [...charset].filter(c => !AMBIG.has(c)). It's a small accessibility courtesy that trades a sliver of entropy for a meaningfully lower chance of a frustrated retry-and-lockout cycle.

A five-item history that survives "oops, I meant the last one"

Every freshly generated password is unshifted onto the front of a history array, then the array is trimmed to five with .pop() — the same newest-first, fixed-length pattern used by the Emoji Picker's recent tab. It solves a real annoyance: clicking "Generate" one too many times no longer means the good password is gone forever, since each entry in the list carries its own copy button.

Step by step

How to Use

  1. 1
    Click "Generate password" to create a random passwordA cryptographically random password appears in the monospace output field. The strength meter updates immediately. The password is added to the recent history list below.
  2. 2
    Adjust the length slider and checkboxesMove the slider between 8 and 32 characters. Check or uncheck uppercase, lowercase, numbers, symbols, and exclude-similar. Each checkbox change regenerates the current password automatically.
  3. 3
    Click Copy to copy to clipboardThe Copy button copies the displayed password. It turns green and shows "Copied!" for 2 seconds. Each history item also has its own copy button.
  4. 4
    Use the history to recover a previous passwordThe 5 most recent passwords appear below the generator. Click any copy button to copy a previous password. Clear all history with the Clear button.
  5. 5
    Use for a registration form default passwordCall generate() on page load to pre-fill a suggested password in a registration form. Wire the generated value to a hidden input that submits with the form.
  6. 6
    Export in your formatClick "HTML" for a standalone page, "JSX" for a React component with useState for password and options, or "Tailwind" for a Tailwind CSS version.

Real-world uses

Common Use Cases

Account registration and setup password suggestion
Show the generator as a "Suggest a strong password" link on registration forms. When clicked, the generated password fills the password field. The strength meter confirms the quality before the user accepts.
Admin panel credential generation for new accounts
When an admin creates a new user account, the password generator creates a temporary strong password. The admin copies it to share with the user who resets it on first login.
API key and secret generation preview
Adapt for generating API keys by using only alphanumeric characters (no symbols), setting a fixed length (32 chars), and excluding similar characters for better transcription. The copy button integrates with credential delivery workflows.
Security settings and password policy compliance tool
Embed in a security settings page where users are prompted to update weak passwords. The strength meter shows the policy requirements visually. Pre-check the required character types to enforce minimum complexity.
Study crypto.getRandomValues() vs Math.random()
The generator demonstrates why Math.random() is inappropriate for security-sensitive use cases. crypto.getRandomValues() reads from the OS entropy pool (hardware noise, timing jitter) to produce genuinely unpredictable values.
Passphrase and invite code generator
Change the charset to only uppercase letters for invite codes (FJKM-QLRT-BXNW), or use numbers only for PIN generation. The exclude-similar option is especially valuable for invite codes that users must type manually.
Related: Two-Factor Authentication Setup Flow
See the Two-Factor Authentication Setup Flow for a related forms pattern worth pairing with this one.

Got questions?

Frequently Asked Questions

Math.random() uses a deterministic pseudo-random number generator (PRNG) — given the initial seed value, an attacker who observes several outputs can predict future values. crypto.getRandomValues() reads from the operating system entropy pool, which gathers entropy from hardware events (disk timing, network packet timing, mouse movement). This makes the output genuinely unpredictable and safe for cryptographic use. Always use crypto.getRandomValues() for passwords, tokens, keys, and any security-sensitive random generation.

crypto.getRandomValues(new Uint32Array(length)) fills an array with random 32-bit unsigned integers (0 to 4,294,967,295). Each integer is mapped to a character via charset[n % charset.length]. Modulo is used because it wraps the large integer into the charset range. The distribution is not perfectly uniform (there is a slight bias if 4,294,967,295 is not divisible by charset.length), but for practical password lengths and charsets, the bias is negligible — less than 0.000001%.

Add an input for the password: <input type="password" id="pw-field">. After generating: document.getElementById("pw-field").value = currentPw. Fire an input event so any listeners (React, validators) see the change: field.dispatchEvent(new Event("input", { bubbles: true })). If using a confirm-password field, set both fields to the same value. The user can then edit the suggested password or accept it as-is.

Save the options (length, character set checkboxes) to localStorage: function saveOptions() { localStorage.setItem("pwgen_opts", JSON.stringify({ len: +lenRange.value, upper: upperCheck.checked, ...}) }. Call saveOptions() on every option change. On page load: const saved = JSON.parse(localStorage.getItem("pwgen_opts")); if (saved) restoreOptions(saved). The history array can also be persisted: localStorage.setItem("pwgen_history", JSON.stringify(history)).