DEV Community

Jason Oboti
Jason Oboti

Posted on

Create a password generator with Vanilla JS, Html and css

Note worthy 📝

Let's Start

  • First open up your favorite code editor...I use Vs code, you could use any that your familiar with

  • Create a folder with the project name which we would call

password-generator.

  • Open the folder and create the index.html file for our markup.

  • Using the emmet key of shift key + ! you would get something like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the body tag create the skeleton of the page that looks like this

    <div class="container">
      <h2>Password Generator</h2>
      <div class="result-container">
        <span id="result"></span>
        <button class="btn" id="clipboard">
          <i class="far fa-clipboard"></i>
        </button>
      </div>
      <div class="settings">
        <div class="setting">
          <label>Password length</label>
          <input type="number" id="length" min="4" max="20" value="20" />
        </div>
        <div class="setting">
          <label>Include uppercase letters</label>
          <input type="checkbox" id="uppercase" checked />
        </div>
        <div class="setting">
          <label>Include lowercase letters</label>
          <input type="checkbox" id="lowercase" checked />
        </div>
        <div class="setting">
          <label>Include numbers</label>
          <input type="checkbox" id="numbers" checked />
        </div>
        <div class="setting">
          <label>Include symbols</label>
          <input type="checkbox" id="symbols" checked />
        </div>
      </div>
      <button class="btn btn-large" id="generate">Generate password</button>
    </div>
Enter fullscreen mode Exit fullscreen mode
  • Then we move to the CSS for styling

  • Create a new file and name it style.css

  • Now link the CSS file to the html page by attaching <link rel="stylesheet" href="style.css" /> in the <head> tag

we would set Our CSS box and body properties now

* {
    box-sizing: border-box;
}

body {
    background-image: linear-gradient(110deg, #f01313, rgb(97, 167, 18));
    color: #fff;
    display: flex;
    font-family: 'Varela Round', sans-serif;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 10px;
    min-height: 100vh;
    overflow: hidden;
}
Enter fullscreen mode Exit fullscreen mode
  • I used a linear gradient, you could play around wirh the colors tho.

  • Set the p, h and input tags to your preferred style

p {
    margin: 5px 0;
}

h2 {
    margin: 10px 0 20px;
    text-align: center;
}

input[type=checkbox] {
    margin-right: 0;
}
Enter fullscreen mode Exit fullscreen mode

Now the rest of the styling

.container {
    background-image: linear-gradient(110deg, rgb(58, 18, 167), #d74242);
    box-shadow: 0px 5px 10px rgba(227, 212, 212, 0.338);
    padding: 20px;
    width: 350px;
    max-width: 100%;
}

.result-container {
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    position: relative;
    font-size: 18px;
    letter-spacing: 1px;
    padding: 12px 10px;
    height: 50px;
    width: 100%;
}

.result-container #result {
    word-wrap: break-word;
    max-width: calc(100% - 40px);
}

.result-container .btn {
    font-size: 20px;
    position: absolute;
    top: 5px;
    right: 5px;
    height: 40px;
    width: 40px;
}

.btn {
    border: none;
    color: #fff;
    cursor: pointer;
    font-size: 16px;
    padding: 8px 12px;
    background-color: #4a244a;
}

.btn-large {
    display: block;
    width: 100%;
}

.setting {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 15px 0;
}

@media screen and (max-width: 400px) {
    .result-container {
        font-size: 14px;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • We are done with the styling... initiate more design ides were possible

Now we move to the Javascript

  • Create a file named app.js and link it to the html at the bottom of the page in between the closing </body> and </html> tags, like:
<script src="main.js"></script>
Enter fullscreen mode Exit fullscreen mode
  • In the app.js file, we first manipulate the DOM by getting the elements by the Id names in the html:
const resultEl = document.getElementById('result');
const lengthEl = document.getElementById('length');
const uppercaseEl = document.getElementById('uppercase');
const lowercaseEl = document.getElementById('lowercase');
const numbersEl = document.getElementById('numbers');
const symbolsEl = document.getElementById('symbols');
const generateEl = document.getElementById('generate');
const clipboard = document.getElementById('clipboard');
Enter fullscreen mode Exit fullscreen mode

Now we have to make the styled page to be a working active page

const randomFunc = {
    lower: getRandomLower,
    upper: getRandomUpper,
    number: getRandomNumber,
    symbol: getRandomSymbol
}

clipboard.addEventListener('click', () => {
    const textarea = document.createElement('textarea');
    const password = resultEl.innerText;

    if(!password) { return; }

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

generate.addEventListener('click', () => {
    const length = +lengthEl.value;
    const hasLower = lowercaseEl.checked;
    const hasUpper = uppercaseEl.checked;
    const hasNumber = numbersEl.checked;
    const hasSymbol = symbolsEl.checked;

    resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, length);
});

function generatePassword(lower, upper, number, symbol, length) {
    let generatedPassword = '';
    const typesCount = lower + upper + number + symbol;
    const typesArr = [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]);

    // Doesn't have a selected type
    if(typesCount === 0) {
        return '';
    }

    // create a loop
    for(let i=0; i<length; i+=typesCount) {
        typesArr.forEach(type => {
            const funcName = Object.keys(type)[0];
            generatedPassword += randomFunc[funcName]();
        });
    }

    const finalPassword = generatedPassword.slice(0, length);

    return finalPassword;
}

function getRandomLower() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}

function getRandomUpper() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}

function getRandomNumber() {
    return +String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}

function getRandomSymbol() {
    const symbols = '!@#$%^&*(){}[]=<>/,.'
    return symbols[Math.floor(Math.random() * symbols.length)];
}

Enter fullscreen mode Exit fullscreen mode
  • First we create Event listeners for the clipboard and buttons... wait I forgot to attach the font awesome code for the clipboard.
    Here it is <script
    src="https://kit.fontawesome.com/db3fa2690b.js"
    crossorigin="anonymous"

    to be attached before or after the other <script> tag in the html

  • Now the clipboard

clipboard.addEventListener('click', () => {
    const textarea = document.createElement('textarea');
    const password = resultEl.innerText;

    if(!password) { return; }

    textarea.value = password;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    textarea.remove();
    alert('Password copied to clipboard');
});
Enter fullscreen mode Exit fullscreen mode

Then we add Event listeners to the generate button, here we created a const variable with the value that

  1. Checks the length of the password
  2. Put a check mark on the lowercaseEl, uppercaseEl, numbersEl, symbolsEl elements with a value of checked
generate.addEventListener('click', () => {
    const length = +lengthEl.value;
    const hasLower = lowercaseEl.checked;
    const hasUpper = uppercaseEl.checked;
    const hasNumber = numbersEl.checked;
    const hasSymbol = symbolsEl.checked;

    resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, length);
});
Enter fullscreen mode Exit fullscreen mode
  • Now we write a function that generates random password
function generatePassword(lower, upper, number, symbol, length) {
    let generatedPassword = '';
    const typesCount = lower + upper + number + symbol;
    const typesArr = [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]);

    // Doesn't have a selected type
    if(typesCount === 0) {
        return '';
    }

    // create a loop
    for(let i=0; i<length; i+=typesCount) {
        typesArr.forEach(type => {
            const funcName = Object.keys(type)[0];
            generatedPassword += randomFunc[funcName]();
        });
    }

    const finalPassword = generatedPassword.slice(0, length);

    return finalPassword;
}
Enter fullscreen mode Exit fullscreen mode

Now create random numbers from the character code encoding

function getRandomLower() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}

function getRandomUpper() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}

function getRandomNumber() {
    return +String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}

function getRandomSymbol() {
    const symbols = '!@#$%^&*(){}[]=<>/,.'
    return symbols[Math.floor(Math.random() * symbols.length)];
}
Enter fullscreen mode Exit fullscreen mode
  • We have to get back to the top now and create a new variable object that stores the random function
const randomFunc = {
    lower: getRandomLower,
    upper: getRandomUpper,
    number: getRandomNumber,
    symbol: getRandomSymbol
}
Enter fullscreen mode Exit fullscreen mode

Hurray 🥳

  • Now we've successfully built a password generator... this is one of my first projects in my coding journey So I decided to share it here

Check out the source on GitHub: https://github.com/JasonOboti/Password-Generator

If you followed along you should have something like this

Image description

Top comments (0)