DEV Community

Divyamcm
Divyamcm

Posted on

PASSWORD GENERATOR using HTML, CSS, and Javascript

==================================================

Photo by Markus Spiske on Unsplash

Dear Reader,

Let’s build a password generator which generate passwords of different lengths and which can include or exclude special characters in the generated passwords based on user selection. This is going to be simple. Stay with me till the end. 🔐

Folder structure:

  1. index.html — contains the HTML layout which defines the element structure that would be shown on the page.
  2. style.css- contains CSS code for styling. Using CSS we can style the different portions to make them more visually appealing.
  3. script.js — contains Javascript code where all the functions are placed.

HTML Layout

Open VSCode and create the basic HTML structure in an index.html file by pressing ! and then pressing tab. Give the title as ‘Password Generator’. Link style.css and script.js to the created HTML file and link FontAwesome CSS to use icons*.*

Generate Password Button: Create button inside div class wrapper clicking on which we will generate the password. Add <i class=”fab fa-keycdn”></i> to display icon.

<button id="generate" class="action-btn">Generate Password <i class="fab fa-keycdn"></i></button>
Enter fullscreen mode Exit fullscreen mode

Slider to select length: Add one more div class slider_main inside wrapper class .slider_main class contains the slider which is used to select the length of the password. The min, max and the initial value is set and the selected value using slider will be displayed in the output section.

<div class="slider\_main">
 <input type="range" value="8" min="1" max="25" class="slider"oninput="this.nextElementSibling.value = this.value" id="slider">
 <output>8</output>
</div>
Enter fullscreen mode Exit fullscreen mode

Checkbox to include special characters: Add an input tag of type checkbox, on checking we will include special characters in the password, and on unchecking we will remove special characters from password.

<label class="container" style="font-family: fantasy;color: rgb(3, 3, 3);">Include special characters
            <input type="checkbox" checked="checked" id="checkbox">
            <span class="checkmark"></span>
        </label>
Enter fullscreen mode Exit fullscreen mode

Password display and copy button: Add a h5 tag under div class wrapper_main to display the generated password and add a button to copy the generated password. Use <i class=”fas fa-clipboard”> for the clipboard icon.

<div class="wrapper_main">
        <h5 id="pwd_txt"></h5>
        <button id="clipboard" class="clipboard">
            <i class="fas fa-clipboard"></i>
        </button>
</div>
Enter fullscreen mode Exit fullscreen mode

Here is the complete HTML code,

 <!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>Password Generator</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
     <link rel="stylesheet" href="style.css"> 
</head>

<body>
    <div class="wrapper">
        <button id="generate" class="action-btn">
            Generate Password <i class="fab fa-keycdn"></i>
        </button>
        <div class="slider_main">
            <input type="range" value="8" min="1" max="25" class="slider"
                oninput="this.nextElementSibling.value = this.value" id="slider">
            <output>8</output>
        </div>
        <label class="container" style="font-family: fantasy;color: rgb(3, 3, 3);">Include special characters
            <input type="checkbox" checked="checked" id="checkbox">
            <span class="checkmark"></span>
        </label>
    </div>



    <div class="wrapper_main">
        <h5 id="pwd_txt"></h5>
        <button id="clipboard" class="clipboard">
            <i class="fas fa-clipboard"></i>
        </button>
    </div>
    <script src="script.js"></script>
</body>

</html> 

Enter fullscreen mode Exit fullscreen mode

CSS Styling

Implement a slider to override the default one and hovering on the slider will make it less opaque.

.slider{

-webkit-appearance: none;
width: 70%;
height: 10px;
background: #f7be04;
border-radius: 15px;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
margin-left: 40px;
margin-top: 25px;
margin-bottom: 20px;
}

.slider:hover{
opacity: 0.5;
}
Enter fullscreen mode Exit fullscreen mode

Complete CSS code is here

html{
min-height: 100%;
}



body{
min-height: 100%;
background-color: #2d3436;
background-image: linear-gradient(315deg, #2d3436 0%, #000000 74%);
text-align: center;
}



.slider{
-webkit-appearance: none;
width: 70%;
height: 10px;
background: #f7be04;
border-radius: 15px;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
margin-left: 40px;
margin-top: 25px;
margin-bottom: 20px;
}

.slider:hover{
opacity: 0.5;
}

.slider::-webkit-slider-thumb{
-webkit-appearance: none;
width: 15px;
height: 15px;
background: #000000;
border-radius: 50%;
cursor: pointer;
}

.action-btn{
background-color: #000;
border: 0;
color: #f7be04;
font-size: 20px;
cursor: pointer
padding: 10px;
margin: 10px  20px;
border-radius: 15px;
font-family: fantasy;
opacity: 1;
transition: opacity .2s;
}



.action-btn:hover{
opacity: 0.5;
}



.wrapper{
display: flex;
background-color: rgb(253, 253, 252);
flex-direction: column;
width: 30%;
margin-top: 10%;
margin-left: 35%;
border-radius: 15px;
font-family: fantasy;
padding-bottom: 1%;
}

.slider_main{
display: flex;
flex-direction: row;
}

output{
margin-top: 20px;
margin-left: 10px;
}



.wrapper_main
{
display: flex;
background-color: rgb(253, 253, 252);
flex-direction: row;
width: 22%;
margin-top: 5%;
margin-left: 38%;
border-radius: 15px;
font-family: Georgia, serif;
padding-left: 45px;
}



.clipboard{
margin-left: auto;
cursor: pointer;
border: 0;
background-color: white;
color:black;
border-radius: 15px;
font-size: 23px;
opacity: 1;
transition: opacity .2s;
}



.clipboard:hover{
opacity: 0.5;
}
Enter fullscreen mode Exit fullscreen mode

Javascript logic

We need to generate the password by selecting characters randomly. The length slider value given by the user will determine the length of the password and the user can choose whether to include special characters or not using the checkbox. To implement this functionality let’s fetch the required elements and store them in the below constants and variables.

password_ele — To store the h5 element which is used to set the generated password.

string — To store the characters used to generate passwords except for special characters.

special_chars —Used to store special characters, based on check box value we can add special characters to the password.

generate — Used to store the Generate Password button.

clipboard — Used to store clipboard button.

pwd_length — Used to store the slider element.

const password_ele = document.getElementById("pwd_txt");

var string = "ABCDEFGHIJKLMNOPQRSTUVWXYZacdefghijklnopqrstuvwxyz0123456789";

const special_chars = "@#$%^&*";

const generate = document.getElementById("generate");

const clipboard = document.getElementById("clipboard");

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

On clicking Generate Password button we will execute some lines of codes to generate the password using Math.random() function. If checkbox is checked then we will add special characters to our original string. Original string contains “ABCDEFGHIJKLMNOPQRSTUVWXYZacdefghijklnopqrstuvwxyz0123456789”.

Loop through the string to fetch the character randomly and in each loop add the randomly selected character to the password variable which was empty initially. The number of times the loop is executed is equal to the slider length so, the length of the password will be equal to the length given by the user.

generate.addEventListener('click', () => {
    let password = "";
    var checked = document.getElementById("checkbox").checked;
    var final_string = string;
    console.log(checked);
    if (checked) {
        final_string += "@#$%^&*";
    }
    for (var i = 0; i < pwd_length.value; i++) {
        let pwd = final_string[Math.floor(Math.random() * final_string.length)];
        password += pwd;
    }
    password_ele.innerText = password;
    final_string = string;
});
Enter fullscreen mode Exit fullscreen mode

on click of clipboard icon, the password text should get selected and display an alert message.



clipboard.addEventListener('click', () => {

 navigator.clipboard.writeText(password_ele.innerText);

 alert("Password copied to clipboard");

});
Enter fullscreen mode Exit fullscreen mode

Complete javascript code is here,

const password_ele = document.getElementById("pwd_txt");
var string = "ABCDEFGHIJKLMNOPQRSTUVWXYZacdefghijklnopqrstuvwxyz0123456789";
const special_chars = "@#$%^&*";
const generate = document.getElementById("generate");
const clipboard = document.getElementById("clipboard");
var pwd_length = document.getElementById("slider");


generate.addEventListener('click', () => {
    let password = "";
    var checked = document.getElementById("checkbox").checked;
    var final_string = string;
    console.log(checked);
    if (checked) {
        final_string += "@#$%^&*";
    }
    for (var i = 0; i < pwd_length.value; i++) {
        let pwd = final_string[Math.floor(Math.random() * final_string.length)];
        password += pwd;
    }
    password_ele.innerText = password;
    final_string = string;
});


clipboard.addEventListener('click', () => {
    navigator.clipboard.writeText(password_ele.innerText);
    alert("Password copied to clipboard");
});


Enter fullscreen mode Exit fullscreen mode

Let’s check the output

Complete code is placed in GitHub.

Thanks for your interest.

Discussion (16)

Collapse
lukeshiru profile image
LUKESHIRU

Hi, @divyamcm ! Can I ask you which tutorial/blogger/YouTuber did you follow to do this? I believe this is the third time I see pretty much the same code in DEV (logic, order of the functions and so on), and instead of writing my tips to fix this for the third time, I would prefer to go to the root of all evil and chat with whoever is "explaining" how to do password generators.

Collapse
jumokee profile image
jumokee

lol nice

Collapse
lukeshiru profile image
LUKESHIRU

I'm asking honestly. Maybe they all got the same "inspiration", I just want to go to the source.

Collapse
divyamcm profile image
Divyamcm Author

Hi @lukeshiru , I haven't referred a single tutorial to write the code. I am beginner and whenever I am stuck, I referred stack overflow and other tutorials.
Please feel free correct my code.😊

Collapse
lukeshiru profile image
LUKESHIRU

Oh that makes sense. I'll look for the top stack overflow answer for password generation. Thanks a lot for the clarification!

Collapse
torbentee profile image
Torben

Hej Divyamcm very nice article 😀
The MDN says Math.random() is not cryptographically secure to use. It suggests using Crypto.getRandomValues()

Collapse
framedoubt profile image
Brandon Wright • Edited on

Thank you for the cool tool share, oh it's built into JavaScript

Collapse
aminmansuri profile image
hidden_dude

Math.random() should not be used for security applications.

See stackoverflow.com/questions/408320...

For ways to get cryptographically secure random generated values.

Collapse
lukeshiru profile image
LUKESHIRU

Wut???? Is not about "purism", is about folks falling into the same bad practices or mistakes we fell in the past, but without actually knowing there are easier/safer/better ways. Is like there is one person out there doing tutorials about how to get out of holes by digging deeper, instead of using the ladder you have just next to you. I doubt the person that's doing the tutorials folks like Divya here are following is doing it with bad intentions, it might be just plain ignorance, and contacting the source is way better than addressing every single person that followed that tutorial.

Collapse
bowero profile image
Robin Martijn

Copying the password to the clipboard is a great touch! 🔥

Collapse
cuellar22 profile image
RAUL CUELLAR MORENO

Great to educational services

lukeshiru profile image
LUKESHIRU • Edited on

Whatever, dude. Whatever. Peace out, god bless!

Collapse
sudcha23 profile image
Sudeep Chauhan

I'm going to plug it in my next code!