-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
87 lines (72 loc) · 2.69 KB
/
app.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const Base_url="https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies";
const dropdown=document.querySelectorAll(".dropdown select");
const btn=document.querySelector("form button");
const fromCurr=document.querySelector(".from select");
const toCurr=document.querySelector(".to select")
const msg=document.querySelector(".msg");
const icon=document.querySelector("i");
document.addEventListener(".load",()=>{
updateExchangeRate();
});
for(let select of dropdown){
for(currcode in countryList){
let newOption=document.createElement("option");
newOption.innerText=currcode;
newOption.value=currcode;
if(select.name ==="from" && currcode==="USD"){
newOption.selected="selected";
}
if(select.name ==="to" && currcode==="INR"){
newOption.selected="selected";
}
select.append(newOption);
}
select.addEventListener("change",(evt)=>{
updateFlag(evt.target);
// evt.target give where change occur
});
}
const updateFlag= (element)=>{
let currcode=element.value;
// console.log(currcode);
let countrycode= countryList[currcode];
//console.log(countrycode);
let newSrc=`https://flagsapi.com/${countrycode}/flat/64.png`
let img=element.parentElement.querySelector("img");
img.src=newSrc;
};
const updateExchangeRate= async()=>{
let amount=document.querySelector(".amount input");
let amtVal=amount.value;
if(amtVal===""||amtVal<1){
amtVal=1;
amount.value="1";
}
const URL=`${Base_url}/${fromCurr.value.toLowerCase()}.json`;
let response=await axios.get(URL);
let rate = response.data[fromCurr.value.toLowerCase()][toCurr.value.toLowerCase()];
let finalAmount=amtVal*rate;
msg.innerText=`${amtVal} ${fromCurr.value}=${finalAmount.toFixed(4)} ${toCurr.value}`
}
btn.addEventListener("click",(evt)=>{
evt.preventDefault();
// to prevent form by doing default action means it will now only perform what we want
updateExchangeRate()
});
window.addEventListener("load",()=>{
updateExchangeRate();
})
icon.addEventListener("click",handleSelectChange)
function handleSelectChange(event) {
if(fromCurr.name==="from" && toCurr.name==="to"){
[toCurr.value,fromCurr.value]=[fromCurr.value,toCurr.value];
let fromImg=countryList[fromCurr.value];
let newSrc=`https://flagsapi.com/${fromImg}/flat/64.png`;
let img1=fromCurr.parentElement.querySelector("img");
img1.src=newSrc;
let toImg=countryList[toCurr.value];
let newSrc2=`https://flagsapi.com/${toImg}/flat/64.png`;
let img2=toCurr.parentElement.querySelector("img");
img2.src=newSrc2;
}
}