How to Make Password Generator In JavaScript
Tags: javascript, beginners, html, css
Published: 2022-09-08 09:56:14

In this article, we will make password generator In JavaScript. We will make this generator to create strong and random password. Here we will have functionality, and it includes some length, uppercase, lowercase, symbols, and numbers. We also add a button, and by clicking it, a random password will be generated. We can also select that which type should be included in this password.

This project is beginner-friendly, and we will only focus on JavaScript. Because this is JavaScript based project, So let’s make it step-by-step.
you can see the demo here [**DEMO**](https://rocoderes.com/how-to-make-password-generator-in-javascript/)

## Pre-requisites to Make Password Generator In JavaScript

- Basic knowledge of HTML.
- Basic knowledge of CSS.
- Good knowledge of JavaScript.

##Setting up The Project

For this project, we need to basically three files. First will be our index.html, in this we will add our elements, and you can simply say we will create the skeleton of the project using HTML file. Then for designing purpose we will be adding our style.css file, with this we will add some styles to our HTML, this is going to be purely based on you, like you can customize it any way. And lastly, our script.js file, this will be our main file because we will add functionality to choose types and generate password using the JavaScript file.

Now in HTML, we will be adding our link for font-awesome, so that we can access some icons in our project like copy icon. After that, we have added our CSS file for basic designing, and also we will add some animation and responsiveness with this CSS file. And lastly we have added our JavaScript file in body part, so that we can access the HTML elements, This is why our JS file in the bottom of the code.

```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <!--=============== CSS ===============-->
    <link rel="stylesheet" href="assets/css/styles.css" />

    <title>Password generator</title>
  </head>
  <body>
     <!--=============== MAIN JS ===============-->
    <script src="assets/js/main.js"></script>
  </body>
</html>
```
Now, after the basic setup of HTML, we will add our a text field, a button, and setting menu for them. For this, we have added a <div> for result field, in this we have added a span tag, and a button in which have added a copy icon. Now we have put settings <div>, in which we will add some other divs for the options. We have added divs for password length, uppercase, lowercase, number, and symbols. Also, we have added input fields to these divs. Then we have checked these all fields, and we added some password length as well. Lastly, we have added a button to generate the password.

```
<div class="container">
      <h2>Password Generator</h2>
      <div class="result-container">
        <span id="result"></span>
        <button class="btn" id="clipboard">
            <i class="fa fa-copy"></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>

```

![Image description](https://i0.wp.com/rocoderes.com/wp-content/uploads/2022/08/Screenshot-701.png?resize=696%2C435&ssl=1)

## Designing Generator Items
As we can see here, the output of our HTML is straight-forward, but it doesn’t look so good. So we will add our custom designs to these elements to make the output very attractive and good. Since this project mainly depends on JavaScript, and designing is purely depending on the user that how does user need this form to look a like, so we don’t get so much in the deep in CSS. You can also apply this below code to make this project similar. Also, we will provide the full source code for this, so you can easily download and use it.

But here let me point out one thing, we have added media query to add responsiveness to this generator. Also, we have added some area to the <span>.

```
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');

* {
	box-sizing: border-box;
}

body {
	background-color: #3B3B98;
	color: #fff;
	display: flex;
	font-family: 'Muli', sans-serif;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 10px;
	min-height: 100vh;
}

p {
	margin: 5px 0;
}

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

input[type=checkbox] {
	margin-right: 0;
}

.container {
	background-color: #23235B;
	box-shadow: 0px 2px 10px rgba(255, 255, 255, 0.2);
	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: #3B3B98;
}

.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;
	}
}
```

![Image description](https://i0.wp.com/rocoderes.com/wp-content/uploads/2022/08/Screenshot-702.webp?resize=696%2C435&ssl=1)

## Setting up Configurable in JavaScript
Since our project looks cool and attractive, let’s add our functionalities using JavaScript. In JavaScript, we have declared some constants, in which we have fetched the divs using document.getElementById() method from HTML. We have fetched all of these divs which are required to complete this generator.

```
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');
```

## Adding Copy to Clipboard Functionality
As we have fetched all the elements, we need to access the clipboard button. We have added a click event, on this event we have applied a function, in which we have create a text area using document.createElement('textarea');. And we have added a constant in which we have to assign the result’s inner text. Then we are checking where the password empty or not. We assigned the password to the text area as its value, And we have appended this text area in the body using this document.body.appendChild(textarea).

Now we have used textarea.select();, so that password will be selected and will get highlighted. Then we will remove this text area using remove() method, And we will add an alert message after it will get triggered when the clipboard will get clicked. Also, this button will work when the password gets generated.

```
clipboard.addEventListener('click', () => {
	const textarea = document.createElement('textarea');
	const password = resultEl.innerText;
	
	if(!password) { return; }
	
	textarea.value = password;
	document.body.appendChild(textarea);
	textarea.select();

	textarea.remove();
	alert('Password copied to clipboard');
});

```

## Randomizing The Password
We have added a function in which we have called all the function to create random password. First, we have added getRandomLower(), in which we are getting random lowercase letter. We used Math.random() * 26 to get random value between 0 and 26, And with Math.floor(Math.random() * 26) + 97 this we will get value between 97 and 122. Lastly, we have used String.fromCharCode() to get string value from this character code.

Similarly, we have returned uppercase letter from getRandomUpper(), random number from getRandomNumber() function. And lastly, we have assigned all the symbols in the getRandomSymbol() and we are just returning a random symbol from this.

```
const randomFunc = {
	lower: getRandomLower,
	upper: getRandomUpper,
	number: getRandomNumber,
	symbol: getRandomSymbol
}
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)];
}
```

## Generating Random Password
Now, after this, we will generate the password. We have added an event listener for click event, in this we have added some constants, in these we have fetched the status of the corresponding types. Like we have used lengthEl.values to get value from the length text area. This will return the string value, but we need the number type, so we used ‘+’ sign before it. Then we have to use lowercaseEl.checked, uppercaseEl.checked, numberEl.checked, and symbolsEl.checked. These we will return true or false value, using these constants we will call the generatePassword() function.

In this function, we have added a constant with empty string, then we have to filter out the unchecked values. We have applied filter using [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]);. Then we have applied a loop till the length of the password generation, we have fetched this value in length constant already.

We have used this line of code const funcName = Object.keys(type)[0]; to fetch the type of the value type, which are checked already. Then we have called the randomFunc() function with the type, Also we have added this string to the password. With this loop we will be able to generate the password, and using the slice method we will remove the spaces which came with generated password.

```
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;
}

```
**Output**

![Image description](https://i0.wp.com/rocoderes.com/wp-content/uploads/2022/08/Accordion.gif?resize=696%2C392&ssl=1)

if you want to full source code please visit [Rocoderes](https://rocoderes.com/how-to-make-password-generator-in-javascript/)