-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (50 loc) · 1.9 KB
/
app.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
const passwordElem = document.getElementById("password"),
lengthElem = document.querySelector("#length"),
lengthTextElem = document.querySelector("#lengthText"),
copyButtonElem = document.querySelector(".copy"),
copyButtonTextElem = document.querySelector(".copy span");
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const characters = {
symbols: "!@#$%^&*(){}[]=<>/,.",
similar: "il1Lo0O",
uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
lowercase: "abcdefghijklmnopqrstuvwxyz",
numbers: "0123456789"
};
const generatePassword = () => {
const passwordArray = [];
const lengthRequired = +lengthElem.value;
const options = Array.from(checkboxes);
const noOptionsChecked = options.every((option) => !option.checked);
hideCopiedMessage();
if (noOptionsChecked) {
passwordElem.value = "select an option";
} else {
while (passwordArray.length < lengthRequired) {
for (const i in checkboxes) {
if (checkboxes[i].checked)
passwordArray.push(getRandomCharacter(checkboxes[i].name));
}
}
const shuffledFinalPassword = passwordArray
.sort((a, b) => 0.5 - Math.random())
.join("")
.slice(0, lengthRequired);
passwordElem.value = shuffledFinalPassword;
}
lengthTextElem.textContent = lengthElem.value;
};
const getRandomCharacter = (optionName) => {
return characters[optionName][
Math.floor(Math.random() * characters[optionName].length)
];
};
const showCopiedMessage = () => (copyButtonTextElem.style.display = "block");
const hideCopiedMessage = () => (copyButtonTextElem.style.display = "none");
copyButtonElem.addEventListener("click", () => {
const input = passwordElem.value;
/* Copy the text inside the text field */
navigator.clipboard.writeText(input);
showCopiedMessage();
});
lengthElem.addEventListener("input", generatePassword);