With everything being more and more connected to everything else these days, password security is so much more important than ever before. That’s why we are going to build a fairly simple JavaScript app that can generate a secure password for you without any effort!
To begin, let’s create a couple of files: index.html, passgen.js and style.css.
Let’s open index.html and paste some basic HTML in there, which can be found in the GitHub repo for this project.
Next, open style.css and paste some premade styles there, which can be found in the GitHub repo
Neither the HTML, or the CSS are important in this tutorial, so I won’t go over them. Feel free to explore them and customize as you see fit.
Now, we get to do the fun stuff! Open passgen.js and let’s start with a few variable declarations:
const passwordDiv = document.querySelector('.generated-pwd-div'); const passwordLenSlider = document.querySelector('.slider'); const passwordLenDisplay = document.querySelector('.pwd-len-display'); const specialCharsElem = document.querySelector('.specialCharsOption'); const numbersElem = document.querySelector('.numbersOption'); const generatePwdBtn = document.querySelector('.generate-pwd-btn');All we are doing here, is grabbing references to the html elements we need to access for this project.
We are grabbing the DIV where we want to place the generated password, the slider with the numeric display next to it, the two checkboxes for numbers and special characters, and finally the button. All pretty standard stuff so far.
Next, we will set up a few more variables we need:
let generatedPwd = ""; const NUMBERS = '0123456789'; const ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const SPECIAL = '!@#$%^&*()+='; let allChars = "";let generatedPwd = “”; and let allChars = “”; are setting up a blank variables to be used for our generated password and all possible characters respectively.
const NUMBERS = ‘0123456789’;
const ALPHA = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’;
and const SPECIAL = ‘!@#$%^&*()+=’; are setting up usable numbers, alpha characters, and special characters respectively for later.
Next we need to set up a couple of event listeners to make things start happening!
passwordLenSlider.addEventListener('input', () => passwordLenDisplay.textContent = passwordLenSlider.value);Now, this one might look a little scary, but it’s just an event listener that listens for any input on the password length slider and then performs an action. The action here being that we are setting the text content of the display next to it, to the value of the slider.
Next, we set an event listener on the “generate” button.
generatePwdBtn.addEventListener('click', () => generatePassword());This one is really simple too… We just listen for click on the button, and run the generatePassword() function, which we will define next.
Now, you could replace the generatePassword() function with a console.log(“hello world!”) to see that log when you click the generate button, and see we are making progress.
Go on, now, don’t be shy! I’ll wait a moment…
Okay, back? Awesome! Let’s move right on now to creating that function we just talked about.
const generatePassword = () => { //Clear previous password and text generatedPwd = ""; passwordDiv.textContent=""; let pwdLen = passwordLenSlider.value; //we will fill this in, in just a moment }So we just created a function, and added three lines in it. generatedPwd = “”;, passwordDiv.textContent=””; and let pwdLen = passwordLenSlider.value; are simply blanking out the generated password variable, setting the generated password div back to empty as well, and grabbing the current value of the slider, respectively. These are important so that we don’t just keep adding the passwords on to each other over and over.
Next we get to something that you might not have seen before, known as the Ternary Operator. In simple terms, it allows you to do a simple conditional check without larger if/else statements.
const generatePassword = () => { //Clear previous password and text generatedPwd = ""; passwordDiv.textContent=""; let pwdLen = passwordLenSlider.value; allChars = ALPHA .concat((specialCharsElem.checked ? SPECIAL : "")) .concat((numbersElem.checked ? NUMBERS : "")); }So we added in a new variable called allChars and we are starting by adding the ALPHA characters to it, because in this case, you will always have the alpha characters.
Next we use .concat() to join another string, using the ternary operator (specialCharsElem.checked ? SPECIAL : “”) to concat the special characters if the checkbox is checked, or an empty string if it is not. We do the same thing for the numbers checkbox as well.
Now we need to split the allChars string that we just created, into an array so we can pick out individual elements from it.
const generatePassword = () => { //Clear previous password and text generatedPwd = ""; passwordDiv.textContent=""; let pwdLen = passwordLenSlider.value; allChars = ALPHA .concat((specialCharsElem.checked ? SPECIAL : "")) .concat((numbersElem.checked ? NUMBERS : "")); let charArray = allChars.split(""); }We do this by adding the line let charArray = allChars.split(“”); to our code, which as you might have guessed, splits the string into an array of individual characters. (We could also split based on a particular letter or symbol if we so chose, by doing something like let charArray = allChars.split(“,”);, which would split on the comma character.)
Okay, stay with me, we don’t have much left!
Next, we need to loop a number of times (in this case, the password length we specified with the slider). For each cycle of the loop we will pick out a random letter from that array we created in the last step.
We do this by adding the following inside the generatePassword() function we have been working on.
for (let i=0; i < pwdLen; i++) { let rand = Math.floor(Math.random() * charArray.length); generatedPwd = `${generatedPwd}${charArray[rand]}`; }In this snippit let rand = Math.floor(Math.random() * charArray.length); simply grabs a random number between 0 and the length of the array of characters.
generatedPwd = `${generatedPwd}${charArray[rand]}`; might look a little scary and/or fancy, but it just using a Template Literal to append the new, random character on to the previous characters of the generated password in a clean way.
Alright, we just have one, final line to add in the end of our function.
passwordDiv.textContent=generatedPwd;Adding this line, will simply set the text of a div to the generated password, so that we can see the password that was generated with all this hard work.
That's it! We are done! You can now generate a random password between 6 and 25 characters, with alpha, numeric and special characters.
Here are a few ways you could customize this to be your own!
- Automatically copy password to the clipboard
- Copy password to the clipboard with a button
- Increase the character limit
- Add more character options
- Change the look and feel
I would love to see any updates you do to this idea! All the code can be found in the GitHub repo