javascript
48 lines · 8 steps
Building a live password strength meter
A debounced input handler scores passwords with zxcvbn and paints a color-coded strength bar in real time.
Explained by
highlit
1const zxcvbn = require('zxcvbn');
2
3const STRENGTH_LABELS = ['Very weak', 'Weak', 'Fair', 'Strong', 'Very strong'];
4const STRENGTH_COLORS = ['#d64545', '#e0803c', '#d9c94c', '#5aa84f', '#2f8f3a'];
5
6function initPasswordMeter(input, meter) {
7 const bar = meter.querySelector('.meter-bar');
8 const label = meter.querySelector('.meter-label');
9 const feedback = meter.querySelector('.meter-feedback');
10 const toggle = meter.querySelector('.toggle-visibility');
11
12 const render = debounce((value) => {
13 if (!value) {
14 bar.style.width = '0%';
15 label.textContent = '';
16 feedback.textContent = '';
17 return;
18 }
19
20 const { score, feedback: hints } = zxcvbn(value);
21 bar.style.width = `${(score + 1) * 20}%`;
22 bar.style.backgroundColor = STRENGTH_COLORS[score];
23 label.textContent = STRENGTH_LABELS[score];
24 feedback.textContent = hints.warning || hints.suggestions[0] || '';
25 }, 150);
26
27 input.addEventListener('input', (e) => render(e.target.value));
28
29 toggle.addEventListener('click', () => {
30 const masked = input.type === 'password';
31 input.type = masked ? 'text' : 'password';
32 toggle.setAttribute('aria-pressed', String(masked));
33 toggle.textContent = masked ? 'Hide' : 'Show';
34 });
35}
36
37function debounce(fn, wait) {
38 let timer;
39 return (...args) => {
40 clearTimeout(timer);
41 timer = setTimeout(() => fn(...args), wait);
42 };
43}
44
45document.querySelectorAll('[data-password-meter]').forEach((meter) => {
46 const input = document.getElementById(meter.dataset.passwordMeter);
47 if (input) initPasswordMeter(input, meter);
48});
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing an expensive scoring call keeps live feedback smooth while the user is still typing.
- 2Mapping a numeric score to parallel label and color arrays turns raw output into clear visual UI.
- 3Wiring behavior from a data attribute lets one initializer serve every meter on the page.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
javascript
function initCharacterCounter(textarea, options = {}) { const maxLength = options.maxLength ?? 280; const warnThreshold = options.warnThreshold ?? 0.9;
A live character counter for textareas
dom
closures
accessibility
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-live-password-strength-meter-explained-javascript-4d7c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.