Random Password Generator in JavaScript

Random Password Generator in JavaScript
Code Snippet:JavaScript Password Generator
Author: Michael Cannon
Published: May 12, 2024
Last Updated: May 12, 2024
Downloads: 53
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a random password generator based on user-selected criteria. It utilizes checkboxes and a dropdown menu for customization. The generated passwords can include uppercase letters, special characters, and numbers. This tool helps create secure passwords quickly.

You can use this code on any website or web application that requires password generation functionality. It provides a simple and customizable way to create strong passwords. This helps enhance the security and user experience on your platform.

How to Create Random Password Generator Javascript

1. First of all, load the Bootstrap CSS by adding the following CDN link into the head tag of your HTML document.

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css'>

2. Create the HTML structure for your password generator. Include the necessary elements such as <h1> for the title, <input> for password display, and <button> for generating passwords. You can also add checkboxes and dropdowns for customization.

<main class="d-flex flex-column align-items-center">
    <h1>Password Generator</h1>
    
    <form class="form-inline">
        <input type="text" class="form-control" id="password" placeholder="Generate Password">
    </form>
    
    <form class="form-inline">
        <button type="button" class="btn btn-primary">Generate</button>
        <button type="button" class="btn btn-outline-primary">Copy</button>
    </form>
    
    <form class="form-inline">
        <div class="form-group">
            <label for="pwLength">Password Length</label>
            <select class="custom-select" id="pwLength">
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option selected="12">12</option>
                <option value="13">13</option>
                <option value="14">14</option>
                <option value="15">15</option>
                <option value="16">16</option>
            </select>
            <label class="form-check-label">
            <input class="form-check-input" type="checkbox" id="caps">
                A-Z
            </label>
            <label class="form-check-label">
            <input class="form-check-input" type="checkbox" id="special">
                !-?
            </label>
            <label class="form-check-label">
            <input class="form-check-input" type="checkbox" id="numbers" checked="checked">
                1-9
            </label>
        </div>
    </form>
</main>

3. Apply styles to enhance the visual appearance of your password generator. You can customize the layout, fonts, and colors to match your website’s design. Utilize CSS classes to target specific elements and make them visually appealing.

body {
  background-color: #E5E5E5;
  height: 100%;
}

main {
  padding-top: 50px;
  text-align: center;
}
main h1 {
  text-transform: uppercase;
  font-family: sans-serif;
  font-weight: 200;
}
main button, main select, main label, main input {
  margin: 0 0.5rem;
}
main form {
  margin-top: 1rem;
}

4. Finally, implement the logic for generating random passwords in JavaScript. Define functions for generating passwords and copying them to the clipboard. Utilize event listeners to trigger password generation and copying actions when buttons are clicked.

document.addEventListener('DOMContentLoaded', function() {
    function copyToClipboard(text) {
        window.prompt('Copy to clipboard: Ctrl+C, Enter', text);
    }

    function generatePass(pwField) {
        var newPassword = '';
        var chars = 'abcdefghijklmnopqrstuvwxyz';
        var pwLength = document.getElementById('pwLength');
        var caps = document.getElementById('caps');
        var special = document.getElementById('special');
        var numbers = document.getElementById('numbers');

        if (caps.checked) {
            chars = chars.concat('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
        }

        if (special.checked) {
            chars = chars.concat('!@#$%^&*');
        }

        if (numbers.checked) {
            chars = chars.concat('123456789');
        }

        for (var i = pwLength.value; i > 0; --i) {
            newPassword += chars[Math.round(Math.random() * (chars.length - 1))];
        }

        pwField.value = newPassword;
    }
    
    var gen = document.querySelector('.btn-primary');
    var copy = document.querySelector('.btn-outline-primary');
    var pwField = document.getElementById('password');
    
    // Why does this work but
    // gen.addEventListener('click', generatePass(pwField));
    // doesn't?
    gen.addEventListener('click', function() {
        generatePass(pwField);
    });
    
    copy.addEventListener('click', function() {
        copyToClipboard(pwField.value);
    });
})

That’s all! hopefully, you have successfully created a Random Password Generator using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment