Build a random password generator app with vanilla JavaScript

Build a random password generator app with vanilla JavaScript

In this blog, I will teach you how to build a random password generator app with vanilla JavaScript.

Video Tutorial

I have made a video about this on my youtube channel.

Please like and subscribe to my channel. It motivates me to create more content like this.

Html

<div class="container">
<form class="form__container">
<h1 class="title">GenPass</h1>
<div class="password__container">
<div class="password__text">adfpajhfjdfkd</div>
<button class="copy__btn" type="button">Copy</button>
</div>
<div class="input__container">
<div class="settings">
<label for="length">length</label>
<input type="number" id="length" min="6" max="64" value="10" />
</div>
<div class="settings">
<label for="uppercase">Uppercase</label>
<input type="checkbox" id="uppercase" checked />
</div>
<div class="settings">
<label for="lowercase">lowercase</label>
<input type="checkbox" id="lowercase" checked />
</div>
<div class="settings">
<label for="numbers">numbers</label>
<input type="checkbox" id="numbers" checked />
</div>
<div class="settings">
<label for="symbols">symbols</label>
<input type="checkbox" id="symbols" checked />
</div>
</div>
<button class="generate__btn" type="submit">Generate</button>
</form>
</div>

CSS

@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
:root {
--primary: #ff6207;
}
html {
font-size: 62.5%;
}
body {
max-width: 100vw;
overflow-x: hidden;
font-family: 'Noto Sans', sans-serif;
}
body,
button {
color: white;
}
button {
cursor: pointer;
text-transform: uppercase;
}
input:focus,
button:focus {
outline: none;
}
.container {
background-color: #1d1d1d;
min-height: 100vh;
display: grid;
place-items: center;
}
.form__container {
background-color: #0b0b0b;
width: 95%;
max-width: 60rem;
padding: 5rem 3rem;
border-radius: 1rem;
-webkit-box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);
-moz-box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);
box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);
}
.title {
text-align: center;
margin-bottom: 2rem;
font-size: 3rem;
}
.password__container {
display: flex;
background: #f02b09;
padding: 1.5rem;
margin-bottom: 1rem;
align-items: center;
}
.copy__btn {
flex-basis: 20%;
min-width: 7rem;
padding: 0.5rem 0;
background-color: var(--primary);
border: none;
}
.password__text {
flex-grow: 1;
font-size: 1.7rem;
word-break: break-word;
}
.input__container {
margin: 2rem 0;
}
.settings {
display: flex;
justify-content: space-between;
margin-bottom: 1.5rem;
}
label {
font-size: 1.8rem;
margin-right: 1rem;
}
.generate__btn {
background-color: var(--primary);
padding: 1rem;
border: none;
border-radius: 0.5rem;
width: 100%;
}
#length {
text-align: center;
}

JavaScript

First, we need to create functions that will generate random functions.

const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min
const getRandomNum = () => getRandomInt(0, 9)
const caseRanges = {
lower: [97, 122],
upper: [65, 90],
}
const getRandomChar = range => String.fromCharCode(getRandomInt(...range))
const getLowerChar = () => getRandomChar(caseRanges.lower)
const getUpperChar = () => getRandomChar(caseRanges.upper)
const getRandomSymbol = () => {
const symbols = '!@#$%^&*()_+{}[]|:;<>?/'
const index = getRandomInt(0, symbols.length - 1)
return symbols.charAt(index)
}
const randomFuncs = {
lower: getLowerChar,
upper: getUpperChar,
symbol: getRandomSymbol,
number: getRandomNum,
}

Explanation;

  • getRandomInt function will give us a random Integer in a range. If you don't know how to generate random numbers in JavaScript, you can check this blog from my website.

https://www.culescoding.space/blog/generate-random-numbers-in-javascript

Generate random numbers in JavaScript by Cules Coding

  • getRandomChar will give us a random letter. Every character is mapped to a char code. We can use that char code to get a character. You can see the char code reference from here . We will generate a random char code that will give us a letter.

  • And finally, we are storing the function in an object. Later we will see why this is useful.

Get necessary dom elements

// elements
const copyBtnEl = document.querySelector('.copy__btn')
const passwordTextEl = document.querySelector('.password__text')
const generateBtnEl = document.querySelector('.generate__btn')
const formEl = document.querySelector('.form__container')
const lengthEl = document.getElementById('length')
const upperCaseEl = document.getElementById('uppercase')
const lowerCaseEl = document.getElementById('lowercase')
const symbolsEl = document.getElementById('symbols')
const numbersEl = document.getElementById('numbers')

Get the necessary random functions

const getRandomFuncs = () => {
const values = {
lower: lowerCaseEl.checked,
upper: upperCaseEl.checked,
symbol: symbolsEl.checked,
number: numbersEl.checked,
}
const keys = Object.keys(values)
const selectedFuncs = []
keys.forEach(key => {
const value = values[key]
if (value) selectedFuncs.push(randomFuncs[key])
})
return selectedFuncs
}

Explanation:

  • We need to separate the random functions that are needed to generate the password. For example, if the user only wants numbers and symbols in their password, then you only need two random functions.

    1. getRandomNum
    2. getRandomSymbol
  • We are storing the values of the checkbox input in the values object. Values object has to have the same structure as our randomFuncs object.

  • If any property value is true, then we will use the property to get the necessary function from randomFuncs object. Then we will store them in the selectedFuncs array. Then we return that array.

Create the generate password functions

const generatePassword = () => {
const passwordLength = lengthEl.value
const funcs = getRandomFuncs()
const funcslength = funcs.length
let password = ''
if (!funcslength) return password
while (password.length < passwordLength) {
const randomFunc = funcs[getRandomInt(0, funcslength - 1)]
password += randomFunc()
}
return password
}

Explanation:

  • We will run a loop until our password length is less than the given passwordLength.
  • On every loop, we will randomly pick a random function.
  • Then we will call the random function which will return us a character. We will append that character in our password string.

Write password to the screen

const writePassword = () => {
const password = generatePassword()
passwordTextEl.innerText = password
}
writePassword()
formEl.addEventListener('submit', event => {
event.preventDefault()
writePassword()
})

Copy password to the clipboard

const copyToClipBoard = async () => {
const password = passwordTextEl.innerText
if (!password) return false
await navigator.clipboard.writeText(password)
copyBtnEl.innerText = 'Copied!'
setTimeout(() => {
copyBtnEl.innerText = 'Copy'
}, 1500)
}
copyBtnEl.addEventListener('click', copyToClipBoard)

And our password generator is done.

Final product.

password generator by cules Coding

Shameless Plug

Want to create your own blog? Well, I am creating a video series where you will learn about how to create a JAMstack blog with Nextjs and Chakra-UI.

Lessons

Demo

You can demo the website from here

Features

  • Static Blog pages will make the website load faster.
  • Blogs will have code blocks with syntax highlighting and many embed components like youtube videos, GitHub gist, Tweets, and so many other things.
  • Autocomplete search feature for the blog posts.
  • Real-time view counter and so on.

Please like and subscribe to Cules Coding. It motivates me to create more content like this.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

By the way, I am looking for a new opportunity in a company where I can provide great value with my skills. If you are a recruiter, looking for someone skilled in full-stack web development and passionate about revolutionizing the world, feel free to contact me. Also, I am open to talking about any freelance project. I am available on Upwork

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostTop 10 array methods to learn to become a pro in JavaScript
Next PostGenerate random numbers in JavaScript