JavaScript Password Generator Project

In this tutorial, you'll learn to build a Password Generator using JavaScript, HTML, and CSS. This application generates random, secure passwords based on user-selected criteria, including length and the inclusion of uppercase letters, lowercase letters, numbers, and symbols.

Project Setup

Workspace Preparation: Create a folder named password-generator. This dedicated workspace keeps your project files organized.

Create Project Files: Within your project folder, create three files:
  • index.html: Defines the structure and content of your web application.
  • style.css: Styles the application to improve user experience.
  • script.js: Contains the logic for generating passwords and handling user interactions.

Development Process

1. HTML Structure (index.html)

  • Begin with a standard HTML boilerplate. Link your CSS and JavaScript files.
  • Construct a container (div.pw-container) to hold your application's UI.
  • Inside, create sections for displaying the generated password and a form for users to specify their password criteria.
  • Add a button for generating passwords and another for copying the generated password to the clipboard.
Let's open the index.html file and add the following content to it:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Password Generator</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <div class="pw-container">
            <div class="pw-header">
                <div class="pw">
                    <span id="pw">l823Zs78#Css09@</span>
                    <button id="copy">Copy</button>
                </div>
            </div>
            <div class="pw-body">
                <div class="form-control">
                    <label for="len">Password Length</label>
                    <input id="len" value="15" type="number" min="2" max="30" />
                </div>
                <div class="form-control">
                    <label for="upper">Contain Uppercase Letters</label>
                    <input id="upper" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="lower">Contain Lowercase Letters</label>
                    <input id="lower" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="number">Contain Numbers</label>
                    <input id="number" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="symbol">Contain Symbols</label>
                    <input id="symbol" type="checkbox" />
                </div>
                <button class="generate" id="generate">
                    Generate Password
                </button>
            </div>
        </div>
    </body>
</html>

2. Styling (style.css) 

Use a modern, clean aesthetic for your application. 

Consider using CSS variables for colors and font stacks for easier theme management. 

Ensure the application is responsive, providing a good user experience across different devices and screen sizes. 

Style interactive elements (buttons, inputs) to provide visual feedback (e.g., :hover effects).

Let's open the style.css file and add the following content to it:  
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: rebeccapurple;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: "Poppins", sans-serif;
    margin: 0;
    min-height: 100vh;
}

.pw-container {
    background-color: rgb(46, 12, 80);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
    min-width: 400px;
}

.pw-header {
    padding: 1rem;
}

.pw {
    background-color: rgb(69, 28, 109);
    display: flex;
    font-size: 1.5rem;
    align-items: center;
    height: 70px;
    width: 100%;
    position: relative;
    padding: 1rem;
    overflow: auto;
}

.pw button {
    background-color: white;
    border: none;
    color: rgb(29, 2, 56);
    cursor: pointer;
    font-family: inherit;
    font-weight: bold;
    padding: 0.25rem;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(0, 20%);
    transition: opacity 0.2s ease, transform 0.2s ease;
    opacity: 0;
}

.pw:hover button {
    opacity: 1;
    transform: translate(0, 0%);
}

.pw-body {
    padding: 0 1rem 1rem;
}

.form-control {
    color: #eee;
    display: flex;
    justify-content: space-between;
    margin: 0.75rem 0;
}

.generate {
    background-color: #ecb602;
    border: none;
    color: rebeccapurple;
    cursor: pointer;
    display: block;
    font-size: 1.5rem;
    font-weight: bold;
    padding: 0.75rem;
    margin-top: 1rem;
    width: 100%;
}

JavaScript Logic (script.js) 

Core Functions: 

Character Sets: Define strings containing uppercase letters, lowercase letters, numbers, and symbols for use in the generated passwords. 

Random Character Functions: Implement functions to randomly select characters from each character set. 

Password Generation: Create a function that constructs a password based on selected criteria. Ensure it randomly mixes selected character types to enhance security. 

UI Updates: Write a function to update the displayed password in your application. 

User Interaction Handling: Attach event listeners to the form inputs and buttons to handle changes in criteria and generate passwords. Implement the copy-to-clipboard feature for the generated password, providing feedback to the user once the action is completed.

Let's open the script.js file and add the following content to it:  
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const lowerEl = document.getElementById("lower");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");

const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const lowerLetters = "abcdefghijklmnopqrstuvwxyz";
const numbers = "0123456789";
const symbols = "!@#$%^&*()_+=";

function getLowercase() {
    return lowerLetters[Math.floor(Math.random() * lowerLetters.length)];
}

function getUppercase() {
    return upperLetters[Math.floor(Math.random() * upperLetters.length)];
}

function getNumber() {
    return numbers[Math.floor(Math.random() * numbers.length)];
}

function getSymbol() {
    return symbols[Math.floor(Math.random() * symbols.length)];
}

function generatePassword() {
    const len = lenEl.value;

    let password = "";

    if (upperEl.checked) {
        password += getUppercase();
    }

    if (lowerEl.checked) {
        password += getLowercase();
    }

    if (numberEl.checked) {
        password += getNumber();
    }

    if (symbolEl.checked) {
        password += getSymbol();
    }

    for (let i = password.length; i < len; i++) {
        const x = generateX();
        password += x;
    }

    pwEl.innerText = password;
}

function generateX() {
    const xs = [];
    if (upperEl.checked) {
        xs.push(getUppercase());
    }

    if (lowerEl.checked) {
        xs.push(getLowercase());
    }

    if (numberEl.checked) {
        xs.push(getNumber());
    }

    if (symbolEl.checked) {
        xs.push(getSymbol());
    }

    if (xs.length === 0) return "";

    return xs[Math.floor(Math.random() * xs.length)];
}

generateEl.addEventListener("click", generatePassword);

copyEl.addEventListener("click", () => {
    const textarea = document.createElement("textarea");
    const password = pwEl.innerText;

    if (!password) {
        return;
    }

    textarea.value = password;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    textarea.remove();
    alert("Password copied to clipboard");
});

Testing - Open index.html in Browser 

Let's open the index.html file in the browser, and you will be able to see the following screen:

Comments