Password Generator
Generate passwords for my friend Mike
by trentHarlem
HTML
<div id='container'>
<h1>
Password Generator
</h1>
<!--
a centered box containing a form with input fields for
-->
<button id='submit'>
Generate New Password
</button>
<!-- <p id="password_display"></p>
must be input field so that the copy to clipboard function will work -->
<input type="text" value="" id="password_display" />
</div>
CSS
#container {
margin: 0 auto;
background: #ececec;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-width: 320px;
max-width: 500px;
height: 100vh;
}
#container h1 {
font: bold 24px helvetica;
color: #131313;
margin: 10px;
}
/* select all elements within the container */
#container * {
transition: all 0.3s ease;
}
#submit {
background: lightgreen;
margin: 5px;
padding: 9px;
border: 1px solid #000;
border-radius: 5px;
min-width: 250px;
}
#submit:hover {
background: darkgreen;
color: #ececec;
border: 1px solid whitesmoke;
}
#submit:active {
transform: translateY(4px);
}
#password_display {
background: #fff;
margin: 10px;
padding: 10px;
border: 1px solid #131313;
border-radius: 5px;
font: 1.5em system-ui;
color: #131313;
min-width: 250px;
text-align: center;
}
JavaScript
// write a function that generates and returns a password based on given conditions
// example
// 1. length of the returned password should be 14 characters
// 2. at least 1 character from the password must be integer
// 3. at least 1 character from the password must be special character
// 4 at least 1 character from the password must be upper case
// 5. at least 1 character from the password must be lower case
const password_display = document.getElementById('password_display')
const submit = document.getElementById('submit')
submit.addEventListener('click', function(e) {
// password_display.innerHTML = ''
e.preventDefault()
generatePassword()
})
submit.addEventListener('mousedown', function(e) {
e.preventDefault()
password_display.innerHTML = '...'
submit.innerHTML = 'Generating...'
// switch the button back to 'Generate Password' when the mouse is released
submit.addEventListener('mouseup', function(e) {
e.preventDefault()
submit.innerHTML = 'Generate Password'
})
})
function generatePassword() {
let password = ""
const length = 14
const charset =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]:;?><,./"
for (let i = 0, n = charset.length; i < length; ++i) {
password += charset.charAt(Math.floor(Math.random() * n))
}
password_display.value = password
//console.log(password, password.length)
return password
}
generatePassword()
// log a test
// console.log(generatePassword())