JavaScript Password Generator Code

JavaScript Password Generator Code
Project: JavaScript Password Generator
Author: Michael Cannon
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create a password generator. It sets up event listeners for a password generator and copy to clipboard functionality on a webpage. When the DOMContentLoaded event is fired, the code defines two functions: copyToClipboard and generatePass. generatePass creates a new password by selecting a random set of characters based on certain criteria such as length, capital letters, special characters, and numbers copyToClipboard is a utility function that opens a prompt window with the given text that instructs the user to copy the text.

The code then sets up event listeners for two buttons: one to generate a new password, and one to copy the generated password to the clipboard. When the generate button is clicked, it calls the generatePass function to generate a new password and sets it as the value of the password field. When the copy button is clicked, it calls the copyToClipboard function with the value of the password field as its argument.

How to Create JavaScript Password Generator Code

First of all, load the following assets into the head tag of your HTML document.

<meta name="viewport" content="width=device-width, initial-scale=1"><link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css'>

Create the HTML structure for the password generator as follows:

<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>

Now, style the password generator using the following CSS styles:

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

main {
  padding-top: 50px;
  text-align: center;
background-color: silver;
padding: 40px;
}
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;
}

Finally, add the following JavaScript function for its functionality:

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 integrated the JavaScript code for the password generator. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply