-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathscript.js
More file actions
97 lines (80 loc) · 2.44 KB
/
Copy pathscript.js
File metadata and controls
97 lines (80 loc) · 2.44 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const unitConfig = {
length: {
meter: 1,
kilometer: 1000,
centimeter: 0.01,
mile: 1609.34,
foot: 0.3048
},
weight: {
kilogram: 1,
gram: 0.001,
pound: 0.453592,
ounce: 0.0283495
}
};
const categoryEl = document.getElementById("category");
const fromValueEl = document.getElementById("fromValue");
const toValueEl = document.getElementById("toValue");
const fromUnitEl = document.getElementById("fromUnit");
const toUnitEl = document.getElementById("toUnit");
const swapBtn = document.getElementById("swapBtn");
const messageEl = document.getElementById("message");
function formatUnitName(unit) {
return unit.charAt(0).toUpperCase() + unit.slice(1);
}
function populateUnitOptions() {
const category = categoryEl.value;
const units = Object.keys(unitConfig[category]);
fromUnitEl.innerHTML = "";
toUnitEl.innerHTML = "";
units.forEach((unit, index) => {
const fromOption = document.createElement("option");
fromOption.value = unit;
fromOption.textContent = formatUnitName(unit);
fromUnitEl.appendChild(fromOption);
const toOption = document.createElement("option");
toOption.value = unit;
toOption.textContent = formatUnitName(unit);
toUnitEl.appendChild(toOption);
if (index === 1) {
toUnitEl.value = unit;
}
});
}
function convertValue() {
const rawValue = fromValueEl.value.trim();
const inputValue = Number(rawValue);
if (!rawValue) {
toValueEl.value = "";
messageEl.textContent = "";
return;
}
if (Number.isNaN(inputValue)) {
toValueEl.value = "";
messageEl.textContent = "Please enter a valid number.";
return;
}
const category = categoryEl.value;
const fromUnit = fromUnitEl.value;
const toUnit = toUnitEl.value;
const valueInBaseUnit = inputValue * unitConfig[category][fromUnit];
const converted = valueInBaseUnit / unitConfig[category][toUnit];
toValueEl.value = converted.toFixed(6).replace(/\.?0+$/, "");
messageEl.textContent = "";
}
function swapUnits() {
const previousFromUnit = fromUnitEl.value;
fromUnitEl.value = toUnitEl.value;
toUnitEl.value = previousFromUnit;
convertValue();
}
categoryEl.addEventListener("change", () => {
populateUnitOptions();
convertValue();
});
fromValueEl.addEventListener("input", convertValue);
fromUnitEl.addEventListener("change", convertValue);
toUnitEl.addEventListener("change", convertValue);
swapBtn.addEventListener("click", swapUnits);
populateUnitOptions();