-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
74 lines (60 loc) · 2.15 KB
/
Copy pathapp.js
File metadata and controls
74 lines (60 loc) · 2.15 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
74
let dropdown=document.querySelectorAll(".dropdown select");
let btn=document.querySelector("form button")
let from=document.querySelector(".from select");
let to=document.querySelector(".to select");
let msg=document.querySelector(".msg");
for (let select of dropdown) {
for (let Currcode in countryList) {
let newOption = document.createElement("option");
newOption.innerText = Currcode;
newOption.value = Currcode;
select.appendChild(newOption);
}
}
// Set default values AFTER options are loaded
document.querySelector(".from select").value = "USD";
document.querySelector(".to select").value = "INR";
// Set default flags
changeflag(document.querySelector(".from select"));
changeflag(document.querySelector(".to select"));
// Listen to flag changes
document.addEventListener("change", (event) => {
if (event.target.tagName === "SELECT") {
changeflag(event.target);
}
});
function changeflag(element){
let Currcode=element.value;
let countryCode=countryList[Currcode];
let newImg=`https://flagsapi.com/${countryCode}/flat/64.png`;
let img=element.parentElement.querySelector("img");
img.src=newImg;
}
async function updatExchangeRate(){
let amount=document.querySelector(".amount input");
let amtVal=amount.value;
if(amtVal=="" || amtVal<1){
amtVal=1;
amount.value="1";
}
const url = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${from.value.toLowerCase()}.json`;
try {
let response = await fetch(url);
let data = await response.json();
let rate = data[from.value.toLowerCase()][to.value.toLowerCase()];
console.log(rate);
let finalAmount = (amtVal * rate).toFixed(2);
msg.innerText = `${amtVal} ${from.value} = ${finalAmount} ${to.value}`;
} catch (err) {
msg.innerText = "Error fetching currency data.";
console.error(err);
}
}
btn.addEventListener("click", async (evt)=>{
/// (event) is event when a button is clicked
evt.preventDefault();
updatExchangeRate();
} );
window.addEventListener("load",()=>{
updatExchangeRate();
});