Learn how to make a random password generator using HTML, CSS, and JavaScript. This beginner tutorial includes step-by-step code and tips for strong passwords. Start coding today!
Responsive Contact Form Design using HTML, CSS, and JavaScript: Step-by-Step with Source CodeTable of Contents
In today's online world, strong passwords are key to keeping your accounts safe. A password generator is a handy tool that creates random, hard-to-guess passwords for you. In this guide, we'll show you how to build one using basic web tech: HTML for structure, CSS for style, and JavaScript for the magic that makes it work.
This project is great for beginners who want to practice coding. It helps you learn how to mix these three languages to make something useful. Plus, it's fun and quick to finish!
Prerequisites
Before we start, you should know a bit about:
- Basic HTML: Like tags for buttons and inputs.
- Simple CSS: For colors and layouts.
- Entry-level JavaScript: Things like functions and events.
You'll also need a text editor (like VS Code) and a web browser to test your code. No fancy tools required!
Source Code
Step 1 (HTML Code):
Start with the bones of your page. Create an HTML file called index.html and add this code:
Step 2 (CSS Code):
Make it pretty with a file called styles.css. Use simple styles to keep it clean:
body {
font-family: 'Inter', sans-serif;
}
/* Custom styling for the range slider */
input[type='range'] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 8px;
background: #334155;
border-radius: 9999px;
outline: none;
opacity: 0.8;
transition: opacity 0.2s;
}
input[type='range']:hover {
opacity: 1;
}
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
background: #34d399;
cursor: pointer;
border-radius: 50%;
border: 2px solid #0f172a;
box-shadow: 0 0 10px rgba(52, 211, 153, 0.5);
}
input[type='range']::-moz-range-thumb {
width: 20px;
height: 20px;
background: #34d399;
cursor: pointer;
border-radius: 50%;
border: 2px solid #0f172a;
box-shadow: 0 0 10px rgba(52, 211, 153, 0.5);
}
/* Custom checkbox styling */
.custom-checkbox:checked {
background-color: #34d399;
border-color: #34d399;
}
.custom-checkbox:checked:hover {
background-color: #6ee7b7;
border-color: #6ee7b7;
}
.custom-checkbox:focus {
box-shadow: 0 0 0 3px rgba(52, 211, 153, 0.4);
outline: none;
} Step 3 (JavaScript Code):
Now, add the brain in script.js. This code will create random passwords based on your choices:
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const lengthSlider = document.getElementById('length');
const lengthValue = document.getElementById('length-value');
const passwordDisplay = document.getElementById('password-display');
const generateButton = document.getElementById('generate-button');
const copyButton = document.getElementById('copy-button');
const copyIcon = document.getElementById('copy-icon');
const copyMessage = document.getElementById('copy-message');
// Checkboxes
const uppercaseCheckbox = document.getElementById('uppercase');
const lowercaseCheckbox = document.getElementById('lowercase');
const numbersCheckbox = document.getElementById('numbers');
const symbolsCheckbox = document.getElementById('symbols');
// Strength Indicator
const strengthText = document.getElementById('strength-text');
const strengthBars = document.querySelectorAll('#strength-bars div');
// Character sets
const charSets = {
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
numbers: '0123456789',
symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?',
};
// Update Password Strength Indicator
const updateStrengthIndicator = () => {
let score = 0;
if (uppercaseCheckbox.checked) score++;
if (lowercaseCheckbox.checked) score++;
if (numbersCheckbox.checked) score++;
if (symbolsCheckbox.checked) score++;
const length = parseInt(lengthSlider.value);
if (length >= 12) score++;
if (length >= 16) score++;
let strength = '';
let barColors = [];
if (score <= 2) {
strength = 'WEAK';
barColors = ['bg-red-500'];
} else if (score <= 4) {
strength = 'MEDIUM';
barColors = ['bg-yellow-500', 'bg-yellow-500'];
} else {
strength = 'STRONG';
barColors = [
'bg-emerald-500',
'bg-emerald-500',
'bg-emerald-500',
'bg-emerald-500',
];
}
// For very low scores, can show a different text
if (score < 2 || (length < 8 && score < 3)) {
strength = 'TOO WEAK';
barColors = ['bg-red-500'];
}
strengthText.textContent = strength;
strengthBars.forEach((bar, index) => {
if (index < barColors.length) {
bar.className = `h-6 w-2 rounded-sm ${
barColors[index] || barColors[0]
}`;
} else {
bar.className = 'h-6 w-2 rounded-sm bg-slate-700';
}
});
};
// Generate Password Logic
const generatePassword = () => {
const length = parseInt(lengthSlider.value);
let characterPool = '';
let password = '';
const options = [];
if (uppercaseCheckbox.checked) {
characterPool += charSets.uppercase;
options.push('uppercase');
}
if (lowercaseCheckbox.checked) {
characterPool += charSets.lowercase;
options.push('lowercase');
}
if (numbersCheckbox.checked) {
characterPool += charSets.numbers;
options.push('numbers');
}
if (symbolsCheckbox.checked) {
characterPool += charSets.symbols;
options.push('symbols');
}
if (characterPool === '') {
passwordDisplay.textContent = 'Select options';
updateStrengthIndicator(); // Update strength even if no options
return;
}
// Ensure at least one of each selected type is included
let guaranteedChars = '';
options.forEach((option) => {
const charSet = charSets[option];
guaranteedChars += charSet[Math.floor(Math.random() * charSet.length)];
});
// Fill the rest of the password
for (let i = guaranteedChars.length; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characterPool.length);
password += characterPool[randomIndex];
}
// Combine and shuffle
password = guaranteedChars + password;
password = password
.split('')
.sort(() => 0.5 - Math.random())
.join('');
passwordDisplay.textContent = password;
updateStrengthIndicator();
};
// Update length display on slider input
lengthSlider.addEventListener('input', (e) => {
lengthValue.textContent = e.target.value;
updateStrengthIndicator();
});
// Update strength indicator when options change
[
uppercaseCheckbox,
lowercaseCheckbox,
numbersCheckbox,
symbolsCheckbox,
].forEach((checkbox) => {
checkbox.addEventListener('change', updateStrengthIndicator);
});
// Copy to Clipboard
copyButton.addEventListener('click', () => {
const password = passwordDisplay.textContent;
if (!password || password === 'Select options') return;
// Using document.execCommand as a fallback for iframe environments
const textArea = document.createElement('textarea');
textArea.value = password;
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
copyIcon.classList.add('hidden');
copyMessage.classList.remove('hidden');
setTimeout(() => {
copyIcon.classList.remove('hidden');
copyMessage.classList.add('hidden');
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
document.body.removeChild(textArea);
});
// Event Listeners
generateButton.addEventListener('click', generatePassword);
// Initial state setup
generatePassword();
});Final Output:
Conclusion:
You've just built a cool password generator using HTML, CSS, and JavaScript! This tool helps create strong passwords fast, making your online life safer. It's a great starter project to boost your skills and add to your portfolio.
Try it out, share it with friends, or tweak it to make it your own. Keep practicing, and you'll get better at web coding.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊

