-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
78 lines (64 loc) · 2.37 KB
/
Copy pathscript.js
File metadata and controls
78 lines (64 loc) · 2.37 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
const darkModeToggle = document.getElementById("darkModeToggle");
const tempInput = document.getElementById("tempInput");
const fromUnit = document.getElementById("fromUnit");
const toUnit = document.getElementById("toUnit");
const swapBtn = document.getElementById("swapBtn");
const convertBtn = document.getElementById("convertBtn");
const resultText = document.getElementById("resultText");
if (localStorage.getItem("theme") === "dark") {
document.body.classList.add("dark");
darkModeToggle.textContent = "☀️";
}
darkModeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
const isDark = document.body.classList.contains("dark");
darkModeToggle.textContent = isDark ? "☀️" : "🌙";
localStorage.setItem("theme", isDark ? "dark" : "light");
});
const unitIcons = {
Celsius: "🌡️",
Fahrenheit: "🔥",
Kelvin: "❄️",
};
function stripEmoji(text) {
return text.replace(/[^a-zA-Z]/g, "").trim();
}
function validateForm() {
const isInputFilled = tempInput.value && fromUnit.value && toUnit.value;
const canSwap = fromUnit.value && toUnit.value;
convertBtn.disabled = !isInputFilled;
swapBtn.disabled = !canSwap;
swapBtn.title = canSwap ? "Swap units" : "Select both units to enable swap";
}
tempInput.addEventListener("input", validateForm);
fromUnit.addEventListener("change", validateForm);
toUnit.addEventListener("change", validateForm);
swapBtn.addEventListener("click", () => {
const fromValue = fromUnit.value;
const toValue = toUnit.value;
fromUnit.value = toValue;
toUnit.value = fromValue;
validateForm();
});
convertBtn.addEventListener("click", () => {
const temp = parseFloat(tempInput.value);
const from = stripEmoji(fromUnit.value);
const to = stripEmoji(toUnit.value);
let result;
if (from === to) {
result = temp;
} else if (from === "Celsius") {
result = to === "Fahrenheit" ? (temp * 9) / 5 + 32 : temp + 273.15;
} else if (from === "Fahrenheit") {
result =
to === "Celsius" ? ((temp - 32) * 5) / 9 : ((temp - 32) * 5) / 9 + 273.15;
} else if (from === "Kelvin") {
result = to === "Celsius" ? temp - 273.15 : ((temp - 273.15) * 9) / 5 + 32;
}
resultText.classList.remove("show");
void resultText.offsetWidth;
resultText.textContent = `${temp} ${
unitIcons[from]
} ${from} is ${result.toFixed(2)} ${unitIcons[to]} ${to}`;
resultText.classList.add("show");
});