-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
68 lines (61 loc) · 2.17 KB
/
Copy pathscript.js
File metadata and controls
68 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
const converterInput = document.querySelector('#converter');
const converterBtn = document.querySelector('.converter-btn');
const resetBtn = document.querySelector('.reset-btn');
const swapBtn = document.querySelector('.change-btn');
const resultInfo = document.querySelector('.result');
const errorInfo = document.querySelector('.error-message');
const spanFirst = document.querySelector('.one');
const spanSecond = document.querySelector('.two');
const unitCelsius = '°C';
const unitFahrenheit = '°F';
const swapUnits = () => {
if (spanFirst.textContent === unitCelsius) {
spanFirst.textContent = unitFahrenheit;
spanSecond.textContent = unitCelsius;
resultInfo.textContent = '';
converterInput.value = '';
} else {
spanFirst.textContent = unitCelsius;
spanSecond.textContent = unitFahrenheit;
resultInfo.textContent = '';
converterInput.value = '';
}
};
const convertCelsiusToFahrenheit = temperatureInCelsius => {
const fahrenheit = (temperatureInCelsius * 1.8 + 32).toFixed(1);
resultInfo.textContent = `${temperatureInCelsius}${unitCelsius} to ${fahrenheit}${unitFahrenheit}`;
converterInput.value = '';
errorInfo.style.display = 'none';
};
const convertFahrenheitToCelsius = temperatureInFahrenheit => {
const celsius = ((temperatureInFahrenheit - 32) / 1.8).toFixed(1);
resultInfo.textContent = `${temperatureInFahrenheit}${unitFahrenheit} to ${celsius}${unitCelsius}`;
converterInput.value = '';
errorInfo.style.display = 'none';
};
const convertTemperature = () => {
if (converterInput.value !== '') {
if (spanFirst.textContent === unitCelsius) {
convertCelsiusToFahrenheit(converterInput.value);
} else {
convertFahrenheitToCelsius(converterInput.value);
}
} else {
resultInfo.textContent = '';
errorInfo.style.display = 'block';
}
};
const resetValues = () => {
converterInput.value = '';
resultInfo.textContent = '';
errorInfo.style.display = 'none';
};
const useEnterKey = e => {
if (e.key === 'Enter') {
convertTemperature();
}
};
converterBtn.addEventListener('click', convertTemperature);
swapBtn.addEventListener('click', swapUnits);
resetBtn.addEventListener('click', resetValues);
converterInput.addEventListener('keyup', useEnterKey);