-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (64 loc) · 2.32 KB
/
Copy pathscript.js
File metadata and controls
73 lines (64 loc) · 2.32 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
const URL = 'https://api.frankfurter.dev/v1';
const amount = document.getElementById('amount');
const fromCurrency = document.getElementById('from-currency');
const toCurrency = document.getElementById('to-currency');
const convertButton = document.getElementById('convert-btn');
const rateInfo = document.getElementById('rate-info');
const convertedAmount = document.getElementById('converted-amount');
async function fetchCurrencies() {
try {
const response = await fetch(`${URL}/currencies`);
const data = await response.json();
const currencies = Object.keys(data);
return currencies;
} catch (err) {
console.error('Error fetching currencies:', err);
return;
}
}
document.addEventListener('DOMContentLoaded', async () => {
const currencies = await fetchCurrencies();
if(!currencies) return;
let optionsHTML = '';
currencies.forEach(currency => {
optionsHTML += `<option value="${currency}">${currency}</option>`;
});
fromCurrency.innerHTML = optionsHTML;
toCurrency.innerHTML = optionsHTML;
fromCurrency.value = 'USD';
toCurrency.value = 'EUR';
convertCurrency();
})
async function convertCurrency() {
const amountValue = parseFloat(amount.value);
const fromValue = fromCurrency.value;
const toValue = toCurrency.value;
if(!amountValue || !fromValue || !toValue) return;
if (fromValue === toValue) {
rateInfo.textContent = `1 ${fromValue} = 1 ${toValue}`;
convertedAmount.textContent = `${amountValue} ${fromValue} = ${amountValue.toFixed(2)} ${toValue}`;
return;
}
try {
const response = await fetch(`${URL}/latest?from=${fromValue}&to=${toValue}`);
const data = await response.json();
const rate = data.rates[toValue];
const finalAmount = rate * amountValue;
rateInfo.textContent = `1 ${fromValue} = ${rate} ${toValue}`;
convertedAmount.textContent = `${amountValue} ${fromValue} = ${finalAmount.toFixed(2)} ${toValue}`;
} catch (err) {
console.error('Error converting currency:', err);
}
}
convertButton.addEventListener('click', (e) => {
e.preventDefault();
convertCurrency();
});
function swapCurrencies() {
const temp = fromCurrency.value;
fromCurrency.value = toCurrency.value;
toCurrency.value = temp;
convertCurrency();
}
const swapButton = document.getElementById('swap-btn');
swapButton.addEventListener('click', swapCurrencies);