-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (61 loc) · 2.17 KB
/
script.js
File metadata and controls
70 lines (61 loc) · 2.17 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
// DOM Elements
const temperatureInput = document.getElementById('temperature');
const fromUnitSelect = document.getElementById('fromUnit');
const toUnitSelect = document.getElementById('toUnit');
const convertButton = document.getElementById('convertButton');
const resultDiv = document.getElementById('result');
// Function to check if all fields are filled
function checkFields() {
if (temperatureInput.value && fromUnitSelect.value && toUnitSelect.value) {
convertButton.disabled = false;
} else {
convertButton.disabled = true;
}
}
// Event listeners for field changes
temperatureInput.addEventListener('input', checkFields);
fromUnitSelect.addEventListener('change', checkFields);
toUnitSelect.addEventListener('change', checkFields);
// Temperature conversion logic
function convertTemperature(temp, fromUnit, toUnit) {
let convertedTemp;
// Convert from Celsius
if (fromUnit === 'Celsius') {
if (toUnit === 'Fahrenheit') {
convertedTemp = (temp * 9/5) + 32;
} else if (toUnit === 'Kelvin') {
convertedTemp = temp + 273.15;
} else {
convertedTemp = temp;
}
}
// Convert from Fahrenheit
else if (fromUnit === 'Fahrenheit') {
if (toUnit === 'Celsius') {
convertedTemp = (temp - 32) * 5/9;
} else if (toUnit === 'Kelvin') {
convertedTemp = (temp - 32) * 5/9 + 273.15;
} else {
convertedTemp = temp;
}
}
// Convert from Kelvin
else if (fromUnit === 'Kelvin') {
if (toUnit === 'Celsius') {
convertedTemp = temp - 273.15;
} else if (toUnit === 'Fahrenheit') {
convertedTemp = (temp - 273.15) * 9/5 + 32;
} else {
convertedTemp = temp;
}
}
return convertedTemp.toFixed(2);
}
// Convert button click event
convertButton.addEventListener('click', () => {
const temp = parseFloat(temperatureInput.value);
const fromUnit = fromUnitSelect.value;
const toUnit = toUnitSelect.value;
const result = convertTemperature(temp, fromUnit, toUnit);
resultDiv.textContent = `${temp} ${fromUnit} is ${result} ${toUnit}`;
});