-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
67 lines (55 loc) · 1.83 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// DOM elements
const gen_btn = document.getElementById("gen-btn");
const cp_btn = document.getElementById("cp-btn");
const options = document.getElementsByClassName("option");
const pass_length = document.getElementById("length");
const upper_check = document.getElementById("upper");
const number_check = document.getElementById("number");
const symbol_check = document.getElementById("symbol");
const result = document.getElementById("result");
//values
const letters = 'abcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = `!#$%&()*+,-./:;<=>?@[]^_{|}~`;
var alphabet = '';
var password = '';
function generatePassword() {
if(pass_length.value < 4 || pass_length.value > 20){
alert("Length must be between 4 and 20");
} else {
password=''; //clear password
alphabet = letters;
if(number_check.checked){
alphabet += numbers;
}
if(symbol_check.checked){
alphabet += symbols;
}
for(var x=0; x < pass_length.value; x++) {
password += generateRandomCharacter();
}
result.innerHTML = password;
}
}
function generateRandomCharacter () {
var rand_char = alphabet.charAt(Math.random()*alphabet.length);
if(rand_char >= 'a' && rand_char <= 'z' ){
if(upper.checked && Math.random() > 0.5){
rand_char = rand_char.toUpperCase();
}
}
return rand_char;
}
function copyPassword() {
if(password == ''){
alert("You need to generate a password first!");
} else {
navigator.clipboard.writeText(password);
}
}
generatePassword();
gen_btn.addEventListener("click",generatePassword);
cp_btn.addEventListener("click", copyPassword);
Array.prototype.forEach.call(options, (element) => {
element.addEventListener("change",generatePassword);
});