50projectsIn50days – Day 31: Password Generator
A password generator is composed by a text file and some other characteristics. Besides the style and the html tags the central thing is the functions we find in script.js.
First of all the simplest one the event listener in the clipboard element. The main objective of this elements is to copy the password in the clipboard so you can do with it whatever you want
clipboardEl.addEventListener('click', () => {
const textarea = document.createElement('textarea')
const password = resultEl.innerText
if(!password) { return }
textarea.value = password
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
textarea.remove()
alert('Password Copied to clipboard!')
})
The second event listener is the one added to the button with the id ‘Generate’ General element. Onche it is clicked it evaluate if the check items are checked. The ones that evaluate if they have lower, upper, number or symbol.
After that it call the function generatePassword whith this constant as an argument
generateEl.addEventListener('click', () => {
const length = +lenghtEl.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)
})
Generate the password generate the string which we are going to see in the text box
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])
if(typesCount === 0){
return ''
}
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
}
The variables are the ones that return differents part of the password: getRandomLower, getRandomUpper, getRandomNumber, 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() * 26) + 48)
}
function getRandomSymbol() {
const symbols = '!#$%&()[]{}'
return symbols[Math.floor(Math.random() * symbols.length)]
}
You can see the code in this GitHub Repository: 31.password_generator and the demo of the project is here: Password Generator