-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (47 loc) · 2.13 KB
/
index.js
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
const fromCur = document.querySelector(".from select");
const toCur = document.querySelector(".to select");
const getBtn = document.querySelector("form button");
const exIcon = document.querySelector("form .reverse")
const amount = document.querySelector("form input");
const exRateTxt = document.querySelector("form .result");
// Event listener for currency dropdowns (select)
[fromCur, toCur].forEach((select, i) => {
for(let curCode in Country_List) {
const selected = (i === 0 && curCode === "USD") || (i === 1 && curCode === "GBP") ? "selected" : "";
select.insertAdjacentHTML("beforeend", `<option value="${curCode}" ${selected}>${curCode}</option>`);
}
select.addEventListener("change", () => {
const code = select.value;
const imgTag = select.parentElement.querySelector("img");
imgTag.src = `https://flagcdn.com/48x36/${Country_List[code].toLowerCase()}.png`;
});
});
// Function to get exchange rate from api
async function getExchangeRate() {
const amountVal = amount.value || 1;
exRateTxt.innerText = "Getting exchange rate...";
try{
const response = await fetch(`https://v6.exchangerate-api.com/v6/28eb26c33360cf597ef2e1cd/latest/${fromCur.value}`);
const result = await response.json();
const exchangeRate = result.conversion_rates[toCur.value];
const totalExRate = (amountVal * exchangeRate).toFixed(3);
exRateTxt.innerText = `${amountVal} ${fromCur.value} = ${totalExRate} ${toCur.value}`;
}catch (error){
exRateTxt.innerText = "Something went wrong...";
}
}
// Event listener for button and exchange icon click
window.addEventListener("load", getExchangeRate);
getBtn.addEventListener("click", (e) => {
e.preventDefault();
getExchangeRate();
});
exIcon.addEventListener("click", () => {
[fromCur.value, toCur.value] = [toCur.value, fromCur.value];
[fromCur, toCur].forEach((select) => {
const code = select.value;
const imgTag = select.parentElement.querySelector("img");
imgTag.src = `https://flagcdn.com/48x36/${Country_List[code].toLowerCase()}.png`;
});
getExchangeRate();
});