-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
58 lines (49 loc) · 1.69 KB
/
script.js
File metadata and controls
58 lines (49 loc) · 1.69 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
const temperatureInput = document.querySelector('#temperature');
const unitSelect = document.querySelector('#unit');
const convertButton = document.querySelector('#convert');
const clearButton = document.querySelector('#clear');
const resultDisplay = document.querySelector('#result');
const historyList = document.querySelector('#history');
const history = [];
convertButton.addEventListener('click', () => {
const temperature = parseFloat(temperatureInput.value);
const unit = unitSelect.value;
if (!temperature || isNaN(temperature)) {
alert('Please enter a valid temperature.');
return;
}
let convertedTemperature;
switch (unit) {
case 'celsius':
convertedTemperature = (temperature * 9 / 5) + 32;
break;
case 'fahrenheit':
convertedTemperature = (temperature - 32) * 5 / 9;
break;
case 'kelvin':
convertedTemperature = temperature + 273.15;
break;
default:
convertedTemperature = temperature;
}
resultDisplay.textContent = `${convertedTemperature.toFixed(2)} ${unit}`;
// Add the conversion to the history list.
history.push({
temperature,
unit,
convertedTemperature,
});
// Update the history list in the DOM.
historyList.innerHTML = '';
history.forEach((item) => {
const historyItem = document.createElement('li');
historyItem.textContent = `${item.temperature} ${item.unit} = ${item.convertedTemperature} ${unitSelect.value}`;
historyList.appendChild(historyItem);
});
});
clearButton.addEventListener('click', () => {
temperatureInput.value = '';
resultDisplay.textContent = '';
historyList.innerHTML = '';
history.length = 0;
});