DEV Community

Cover image for Random Password Generator using Javascript
Foolish Developer
Foolish Developer

Posted on • Updated on

Random Password Generator using Javascript

In this article I am going to show you how to create a random password generator with the help of JavaScript code. I have already created many types of JavaScript projects but this is the first time I am creating such a system. If you want to make it then hopefully this article will help you.

Watch Live Preview 👉👉 JavaScript Password Generator

Random Password Generator is a JavaScript project that can generate strong and unique passwords automatically. I made a box in everyone's first web page. I have used a heading or title. Below the title is an input box where the password can be generated.

Then I made two buttons to copy and generate that password. The unit password will be generated each time you click the Generate button. For this I have used JavaScript Math.random and Math.floor method. There is also a copy button that will help you copy the sourcecodes.

If you don't understand what I'm saying then you can definitely watch the video tutorial below. This video will completely help you to know how I made this design.

Hopefully the video tutorial above has helped you to know how to create this (Random Password Generator).
Below I show step-by-step what code I have used for what purpose.
First of all you have to create an HTML and CSS file.

Step 1: Create a box using html code

I have created a box in the web page using the following codes. I have used the background color of the web page as purple and the background color of the box as white.

<div class="box">

</div>
Enter fullscreen mode Exit fullscreen mode
* {
 margin: 0;
 padding: 0;
 user-select: none;
 box-sizing: border-box;
  }

body {
  background-color: #8d0cf7;
  justify-content: center;
  align-items: center;
  display: flex;
  min-height: 100vh;
    }

 .box{
   background-color: white;
   padding-top: 30px;
   padding: 30px;

 }
Enter fullscreen mode Exit fullscreen mode

Create a box using html code

Step 2: Add a heading to that box

As you can see above, I am the first to use a title here. The following HTML and CSS code helped to create and design that title.

<h2>Random Password Generater</h2>
Enter fullscreen mode Exit fullscreen mode
 .box h2{
   margin-bottom: 40px;
   text-align: center;
   font-size: 26px;
   color: #015a96;
   font-family: sans-serif;
 }
Enter fullscreen mode Exit fullscreen mode

Add a heading to that box

Step 3: Create a display using input

Now I have created a small input box using the input function. Everything that will generate the password can be seen in that input box. I have used the height of the box 50 px and width 400px. I have used user-select: none so that the user cannot click on the input box.

<input type="text" name="" placeholder="Create password" id="password" readonly>
Enter fullscreen mode Exit fullscreen mode

input {
 padding: 20px;
 user-select: none;
 height: 50px;
 width: 400px;
 border-radius: 6px;
 border: none;
 border: 2px solid #8d0cf7;
 outline: none;
 font-size: 22px;
 }

input::placeholder{
  font-size: 23px;
 } 
Enter fullscreen mode Exit fullscreen mode

Create a display using input

Step 4: Create two buttons to generate and copy the password

At the end of it all I made two distributions. One button will generate the password and the other will copy the password. I used CSS code to design those two buttons. I have used the height of each button 50 px, width 155px, background color purple and front color white.

<table>
   <th><div id="button" class="btn1"onclick="genPassword()">Generate</div></th>
   <th><a  id="button" class="btn2" onclick="copyPassword()">Copy</a></th>
</table>
Enter fullscreen mode Exit fullscreen mode
#button {
  font-family: sans-serif;
  font-size: 15px;
  margin-top: 40px;
  border: 2px solid #7100cf;
  width: 155px;
  height: 50px;
  text-align: center;
  background-color: #7100cf;
  display: flex;
  color: rgb(255, 255, 255);
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-radius: 5px;  
}

 .btn2{
   margin-left: 85px
 }

#button:hover {
  color: white;
  background-color: black;
}
Enter fullscreen mode Exit fullscreen mode

Create two buttons to generate and copy the password

Step 5: Activate the system using JavaScript code

So far we've only designed it. This time we will make it work using JavaScript code. First I set a variable of the input's ID (password).

var password=document.getElementById("password");
Enter fullscreen mode Exit fullscreen mode

Now I have added all the symbols, numbers and alphabets in var chars which will be used to create random passwords.

Then I used var passwordLength which will indicate how many characters this password will be created with.

 var chars = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var passwordLength = 12;
 var password = "";
Enter fullscreen mode Exit fullscreen mode

Now I will create a random password using for loop. Here Math.random () will help to create random passwords.

 for (var i = 0; i <= passwordLength; i++) {
   var randomNumber = Math.floor(Math.random() * chars.length);
   password += chars.substring(randomNumber, randomNumber +1);
  }
Enter fullscreen mode Exit fullscreen mode

I will associate that password (constant) with the input box. The resulting password will also be seen in the input box.

document.getElementById("password").value = password;
Enter fullscreen mode Exit fullscreen mode

Step 6: Activate the copy button

We have implemented the password generating system and now we will implement the copy button. In the same way we have determined a variable (copyText) of the ID (password) of that input.
Whatever is written in the input box can be copied with the help of the copy button.

function copyPassword() {
  var copyText = document.getElementById("password");
  copyText.select();
  document.execCommand("copy");  
}
Enter fullscreen mode Exit fullscreen mode

Activate the system using JavaScript code

Final JavaScript code

var password=document.getElementById("password");

 function genPassword() {
    var chars = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var passwordLength = 12;
    var password = "";
 for (var i = 0; i <= passwordLength; i++) {
   var randomNumber = Math.floor(Math.random() * chars.length);
   password += chars.substring(randomNumber, randomNumber +1);
  }
        document.getElementById("password").value = password;
 }

function copyPassword() {
  var copyText = document.getElementById("password");
  copyText.select();
  document.execCommand("copy");  
}
Enter fullscreen mode Exit fullscreen mode

I hope I have explained to you in this tutorial how I created this random password system with the help of JavaScript. If you want to know better, you can watch the video tutorial above.

Related Post:

  1. HTML CSS Footer Tutorial
  2. Todo List JavaScript
  3. Simple Stopwatch JavaScript
  4. Skeleton Screen Loading Animation
  5. Javascript Age Calculator
  6. JavaScript Password Generator
  7. Automatic Image Slider in Html CSS
  8. Sidebar Menu Using HTML CSS

You can also download Random Password Generator source code. Please let me know in the comments how you like this design.

Top comments (11)

Collapse
 
loucyx profile image
Info Comment hidden by post author - thread only accessible via permalink
Lou Cyx

Worth mentioning that the passwords generated by a Math.random will never be as secure as something made by actual password generators (those require a bunch more logic). That being said, from the HTML standpoint, you shouldn't use table for layout, and you should use the button element for buttons (not divs nor anchors), and ideally the event listeners should be added from JS, not HTML. Talking about JS, it can be improved a little as well:

JS Snippet
/** @param {string} chars */
const randomCharacter = chars => () =>
    chars[Math.floor(Math.random() * chars.length)];

/** @param {string} chars */
const generatePassword =
    chars =>
    /** @param {number} length */
    length =>
    () =>
        [...Array(length)].map(randomCharacter(chars)).join("");

/** @type {HTMLInputElement} */
const passwordInput = document.querySelector("#password");

const generatePasswordChars = generatePassword(
    "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ"
);
const generatePasswordChars12 = generatePasswordChars(12);

document.querySelector("#generate-button").addEventListener("click", () => {
    passwordInput.value = generatePasswordChars12();
});

document.querySelector("#copy-button").addEventListener("click", () => {
    navigator.clipboard.writeText(passwordInput.value);
});
Enter fullscreen mode Exit fullscreen mode

You can check the result here. If you want to check the code, is here. You might also notice that I used rem instead of px, and CSS custom properties, just to make it a little bit cleaner in the CSS side.

Cheers!

Collapse
 
aleksandar15 profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Aleksandar15

The Author who hidden this comment is a little stupid bastard.

Collapse
 
loucyx profile image
Lou Cyx • Edited

I'm already used to this. There are authors that embrace comments either debating or learning from them, and then you have folks like the author of this article that prefer to hide comments so nobody "exposes" the things wrong in the post. I don't have to tell you which ones will grow as devs an which ones will not 😅

PS: Let's try to keep it civil and let's not insult authors.

Collapse
 
julienripet profile image
Julien ripet

Math.random() is not cryptographically secure, it is recommended to use window.crypto developer.mozilla.org/en-US/docs/W...

Collapse
 
loucyx profile image
Lou Cyx

I mentioned the same thing, but the post was hidden by the author: dev.to/lukeshiru/comment/1gkl5

Collapse
 
aleksandar15 profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Aleksandar15

We all can agree that the author is a bastard.
I was gonna post it simply like that, but it should be mods (or perhaps if he is one) who can hide comments.
He can't be a trustworthy author if he doesn't accept criticizm, FUCK EGOTISTICAL PEOPLE.

To elaborate more, his username is @Foolish-Developer, wait how do i tag him @code_mystery , yep here we go. What else would do you expect?

Collapse
 
opii972 profile image
Cédric Lisima

I recommend to use github.com/ai/nanoid for the password generator usage. As I saw in previous comments Math.random() is not safe and not a cryptographically-secure random number generator.

Collapse
 
darshkul24 profile image
Darsh

Can you give me a 6-digit OTP generator

Collapse
 
code_mystery profile image
Foolish Developer

You have 'var passwordLength = 12;' Replace 'var passwordLength = 5;' Use. Watch the last part of the video to know better.

Collapse
 
sergio_inge profile image
Sergio Martín

What about Step 3?

Collapse
 
sigitnur profile image
Sigit

is this not easy to guess?

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more