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
1<div class="container">2 <form class="form__container">3 <h1 class="title">GenPass</h1>45 <div class="password__container">6 <div class="password__text">adfpajhfjdfkd</div>7 <button class="copy__btn" type="button">Copy</button>8 </div>910 <div class="input__container">11 <div class="settings">12 <label for="length">length</label>13 <input type="number" id="length" min="6" max="64" value="10" />14 </div>1516 <div class="settings">17 <label for="uppercase">Uppercase</label>18 <input type="checkbox" id="uppercase" checked />19 </div>2021 <div class="settings">22 <label for="lowercase">lowercase</label>23 <input type="checkbox" id="lowercase" checked />24 </div>2526 <div class="settings">27 <label for="numbers">numbers</label>28 <input type="checkbox" id="numbers" checked />29 </div>3031 <div class="settings">32 <label for="symbols">symbols</label>33 <input type="checkbox" id="symbols" checked />34 </div>35 </div>3637 <button class="generate__btn" type="submit">Generate</button>38 </form>39</div>
CSS
1@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap');23* {4 padding: 0;5 margin: 0;6 box-sizing: border-box;7}89:root {10 --primary: #ff6207;11}1213html {14 font-size: 62.5%;15}1617body {18 max-width: 100vw;19 overflow-x: hidden;20 font-family: 'Noto Sans', sans-serif;21}2223body,24button {25 color: white;26}2728button {29 cursor: pointer;30 text-transform: uppercase;31}3233input:focus,34button:focus {35 outline: none;36}3738.container {39 background-color: #1d1d1d;40 min-height: 100vh;41 display: grid;42 place-items: center;43}4445.form__container {46 background-color: #0b0b0b;47 width: 95%;48 max-width: 60rem;49 padding: 5rem 3rem;50 border-radius: 1rem;51 -webkit-box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);52 -moz-box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);53 box-shadow: 13px 15px 58px 2px rgba(0, 0, 0, 0.62);54}5556.title {57 text-align: center;58 margin-bottom: 2rem;59 font-size: 3rem;60}6162.password__container {63 display: flex;64 background: #f02b09;65 padding: 1.5rem;66 margin-bottom: 1rem;67 align-items: center;68}6970.copy__btn {71 flex-basis: 20%;72 min-width: 7rem;73 padding: 0.5rem 0;74 background-color: var(--primary);75 border: none;76}7778.password__text {79 flex-grow: 1;80 font-size: 1.7rem;81 word-break: break-word;82}8384.input__container {85 margin: 2rem 0;86}8788.settings {89 display: flex;90 justify-content: space-between;91 margin-bottom: 1.5rem;92}9394label {95 font-size: 1.8rem;96 margin-right: 1rem;97}9899.generate__btn {100 background-color: var(--primary);101 padding: 1rem;102 border: none;103 border-radius: 0.5rem;104 width: 100%;105}106107#length {108 text-align: center;109}
JavaScript
First, we need to create functions that will generate random functions.
1const getRandomInt = (min, max) =>2 Math.floor(Math.random() * (max - min + 1)) + min34const getRandomNum = () => getRandomInt(0, 9)56const caseRanges = {7 lower: [97, 122],8 upper: [65, 90],9}1011const getRandomChar = range => String.fromCharCode(getRandomInt(...range))1213const getLowerChar = () => getRandomChar(caseRanges.lower)14const getUpperChar = () => getRandomChar(caseRanges.upper)1516const getRandomSymbol = () => {17 const symbols = '!@#$%^&*()_+{}[]|:;<>?/'18 const index = getRandomInt(0, symbols.length - 1)1920 return symbols.charAt(index)21}2223const randomFuncs = {24 lower: getLowerChar,25 upper: getUpperChar,26 symbol: getRandomSymbol,27 number: getRandomNum,28}
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
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
1// elements2const copyBtnEl = document.querySelector('.copy__btn')3const passwordTextEl = document.querySelector('.password__text')4const generateBtnEl = document.querySelector('.generate__btn')5const formEl = document.querySelector('.form__container')67const lengthEl = document.getElementById('length')8const upperCaseEl = document.getElementById('uppercase')9const lowerCaseEl = document.getElementById('lowercase')10const symbolsEl = document.getElementById('symbols')11const numbersEl = document.getElementById('numbers')
Get the necessary random functions
1const getRandomFuncs = () => {2 const values = {3 lower: lowerCaseEl.checked,4 upper: upperCaseEl.checked,5 symbol: symbolsEl.checked,6 number: numbersEl.checked,7 }89 const keys = Object.keys(values)1011 const selectedFuncs = []1213 keys.forEach(key => {14 const value = values[key]1516 if (value) selectedFuncs.push(randomFuncs[key])17 })1819 return selectedFuncs20}
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.
getRandomNum
getRandomSymbol
We are storing the values of the checkbox input in the
values
object. Values object has to have the same structure as ourrandomFuncs
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 theselectedFuncs
array. Then we return that array.
Create the generate password functions
1const generatePassword = () => {2 const passwordLength = lengthEl.value34 const funcs = getRandomFuncs()56 const funcslength = funcs.length78 let password = ''910 if (!funcslength) return password1112 while (password.length < passwordLength) {13 const randomFunc = funcs[getRandomInt(0, funcslength - 1)]1415 password += randomFunc()16 }1718 return password19}
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
1const writePassword = () => {2 const password = generatePassword()3 passwordTextEl.innerText = password4}56writePassword()78formEl.addEventListener('submit', event => {9 event.preventDefault()10 writePassword()11})
Copy password to the clipboard
1const copyToClipBoard = async () => {2 const password = passwordTextEl.innerText34 if (!password) return false56 await navigator.clipboard.writeText(password)78 copyBtnEl.innerText = 'Copied!'910 setTimeout(() => {11 copyBtnEl.innerText = 'Copy'12 }, 1500)13}1415copyBtnEl.addEventListener('click', copyToClipBoard)
And our password generator is done.
Final product.
Shameless Plug
I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
Contacts
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: