[ad_1]
Let’s create an absolutely useful foreign money converter utility the use of HTML, CSS, and vanilla JavaScript. By means of the top of this educational, we can have a responsive foreign money app that fetches real-time knowledge with the Trade Charge API and gifts it in a user-friendly interface.
HTML Construction
Our foreign money utility may have a easy interface containing :
- An enter box for the volume to be transformed.
- A drop-down to make a choice the from Foreign money worth
- A 2nd drop-down to make a choice the to foreign money worth
- A convert button
- A
<p>
tag to turn the transformed quantity - A
<p>
tag to turn any mistakes that would possibly happen all through the conversion procedure.
The HTML code will appear to be this:
1 |
<div elegance="container"> |
2 |
|
3 |
<div elegance="currency-container"> |
4 |
<h1>Foreign money converter</h1> |
5 |
<div elegance="input-box"> |
6 |
<label for="quantity">Input quantity</label> |
7 |
<enter sort="textual content" identity="quantity" placeholder="100" required/> |
8 |
</div>
|
9 |
<div elegance="foreign money"> |
10 |
<div elegance="field"> |
11 |
<choose
|
12 |
elegance="select-option" |
13 |
title="from-currency" |
14 |
identity="fromCurrency" |
15 |
>
|
16 |
<possibility worth="USD">United States Buck</possibility> |
17 |
</choose>
|
18 |
</div>
|
19 |
<div>
|
20 |
<span>TO</span> |
21 |
</div>
|
22 |
<div elegance="field"> |
23 |
<choose elegance="select-option" title="to-currency" identity="toCurrency"> |
24 |
<possibility worth="USD">United States Buck</possibility> |
25 |
</choose>
|
26 |
</div>
|
27 |
<button elegance="convert">Convert</button> |
28 |
<p elegance="end result"></p> |
29 |
<p elegance="error"></p> |
30 |
|
31 |
</div>
|
32 |
</div>
|
33 |
</div>
|
Recently, we’re the use of the choice worth as a placeholder. We can exchange and upload extra possibility knowledge dynamically with JavaScript.
Styling With CSS
Let’s get started with some elementary types. We’ve pulled within the somewhat superb Bricolage Ugly font from Google fonts too:
1 |
* { |
2 |
margin: 0; |
3 |
padding: 0; |
4 |
box-sizing: border-box; |
5 |
font-family: 'Bricolage Ugly', sans-serif; |
6 |
}
|
7 |
|
8 |
h1 { |
9 |
font-size: 5em; |
10 |
font-weight: daring; |
11 |
text-align: heart; |
12 |
margin: .5em 0; |
13 |
line-height: .8; |
14 |
}
|
15 |
|
16 |
.container { |
17 |
margin: auto; |
18 |
min-height: 100vh; |
19 |
background-color: #202020; |
20 |
padding: 2em 0; |
21 |
colour: #040203; |
22 |
show: flex; |
23 |
flex-direction: column; |
24 |
align-items: heart; |
25 |
justify-content: heart; |
26 |
}
|
27 |
|
28 |
.currency-container { |
29 |
peak: fit-content; |
30 |
background-color: #7cb889; |
31 |
padding: 3em; |
32 |
border-radius: 40px; |
33 |
}
|
For the enter and label (together with the placeholder within the enter) they are going to have the next types:
1 |
.input-box { |
2 |
show: flex; |
3 |
flex-direction: column; |
4 |
align-items: heart; |
5 |
justify-content: heart; |
6 |
text-align: heart; |
7 |
}
|
8 |
|
9 |
label { |
10 |
font-size: 1.5em; |
11 |
margin-bottom: .4em; |
12 |
}
|
13 |
|
14 |
#quantity { |
15 |
width: 300px; |
16 |
padding: 20px; |
17 |
border-radius: 30px; |
18 |
font-size: 3em; |
19 |
border: 3px cast black; |
20 |
background: clear; |
21 |
colour: black; |
22 |
|
23 |
}
|
24 |
#quantity:center of attention { |
25 |
border: 3px cast white; |
26 |
define: none; |
27 |
}
|
28 |
|
29 |
::placeholder { |
30 |
colour: rgba(0,0,0,0.6); |
31 |
opacity: 1; /* Firefox */ |
32 |
}
|
Subsequent, we can observe styling to the field parts containing the From and To foreign money drop-downs. The drop-down parts will probably be organized in a column structure the use of Flexbox and focused vertically and horizontally. We actually have a hole between the field parts, some padding, and a border radius.
1 |
.foreign money { |
2 |
margin-top: 50px; |
3 |
padding: 20px 20px; |
4 |
show: flex; |
5 |
align-items: heart; |
6 |
justify-content: heart; |
7 |
flex-direction: column; |
8 |
hole: 1.5rem; |
9 |
}
|
10 |
|
11 |
.field { |
12 |
show: flex; |
13 |
align-items: heart; |
14 |
justify-content: heart; |
15 |
}
|
The select-option may have the next types
1 |
.select-option { |
2 |
font-size: 16px; |
3 |
colour: #333; |
4 |
padding: 20px; |
5 |
show: block; |
6 |
font-weight: 700; |
7 |
line-height: 1.3; |
8 |
width: 100%; |
9 |
max-width: 100%; |
10 |
margin: 0; |
11 |
define: none; |
12 |
border-radius: 20px; |
13 |
border: 3px cast black; |
14 |
}
|
In the end, the convert button, the end result, and the mistake message parts may have the next types:
1 |
button { |
2 |
width: 100%; |
3 |
peak: 100px; |
4 |
padding: 10px; |
5 |
border-radius: 30px; |
6 |
border: none; |
7 |
font-size: 1.5em; |
8 |
align-items: heart; |
9 |
background-color: black; |
10 |
colour: #fff; |
11 |
margin-top: 30px; |
12 |
}
|
13 |
.end result { |
14 |
colour: black; |
15 |
font-size: 2.5em; |
16 |
}
|
17 |
.error { |
18 |
colour: #800020; |
19 |
font-size: 12px; |
20 |
}
|
JavaScript Capability
The JavaScript capability may have two portions:
- Getting the foreign money code, foreign money title, and flag from the REST nations API
- getting conversion charge from the Trade Charge API
REST International locations API
The REST nations API supplies an API with the endpoint https://restcountries.com/v3.1/all the place you’ll filter out effects through offering the fields you have an interest in. In our case, we would like the rustic flag, foreign money title, and foreign money code and the endpoint will appear to be this:
1 |
https://restcountries.com/v3.1/all?fields=currencies,flag |
The ensuing pattern knowledge will appear to be this:
1 |
{ |
2 |
"title": { |
3 |
"commonplace": "Eritrea", |
4 |
"professional": "State of Eritrea", |
5 |
"nativeName": { |
6 |
"ara": { |
7 |
"professional": "دولة إرتريا", |
8 |
"commonplace": "إرتريا" |
9 |
}, |
10 |
"eng": { |
11 |
"professional": "State of Eritrea", |
12 |
"commonplace": "Eritrea" |
13 |
}, |
14 |
"tir": { |
15 |
"professional": "ሃገረ ኤርትራ", |
16 |
"commonplace": "ኤርትራ" |
17 |
} |
18 |
} |
19 |
}, |
20 |
"currencies": { |
21 |
"ERN": { |
22 |
"title": "Eritrean nakfa", |
23 |
"image": "Nfk" |
24 |
} |
25 |
}, |
26 |
"flag": "🇪🇷" |
27 |
}, |
To enable you to show our currencies, we can fetch the information and retailer it in a JavaScript record. The script for fetching the information will appear to be this:
1 |
const url = |
2 |
"https://restcountries.com/v3.1/all?fields=title,currencies,flag"; |
3 |
fetch(url) |
4 |
.then((reaction) => reaction.json()) |
5 |
.then((knowledge) => { |
6 |
|
7 |
const end result = []; |
8 |
knowledge.forEach((nation) => { |
9 |
if (Object.keys(nation.currencies).duration >0) { |
10 |
end result.push({ |
11 |
countryname: nation.title.commonplace, |
12 |
title: Object.values(nation.currencies)[0].title, |
13 |
code: Object.keys(nation.currencies)[0], |
14 |
flag: nation.flag, |
15 |
});
|
16 |
}
|
17 |
});
|
18 |
|
19 |
end result.kind((a, b) => a.code.localeCompare(b.code)); |
20 |
const jsonString = JSON.stringify(end result, null); |
21 |
console.log(jsonString); |
22 |
|
23 |
});
|
The code above does the next:
- We use the
fetch()
approach to make an HTTP request to the REST nations API. - Then, we convert the reaction to JSON layout and get started processing the information.
- From the reaction JSON, we first take a look at if each and every nation has a foreign money code since no longer all nations have a foreign money code.
- If a rustic has a foreign money, we create an object with its title, code, and foreign money title and push it to the empty end result array.
- Then we kind the foreign money code alphabetically.
- In the end, we convert the end result to JSON and print the stringified knowledge to the console.
Whilst you run the script in a browser atmosphere, you must be capable of replica the information for your JavaScript record. The knowledge seems like this:



On the other hand, upload this hyperlink for your script the use of the src
characteristic.
Subsequent, let’s get the choose parts.
1 |
let fromCurrency = report.getElementById("fromCurrency"); |
2 |
let toCurrency = report.getElementById("toCurrency"); |
Since we have now the information in an array, it’s now more straightforward to append the currencies to the choice parts of the fromCurrency and toCurrency choose parts.
Create a serve as referred to as addCurrency()
. Within the addCurrency()
serve as, we use the forEach()
serve as to loop during the currencies array; for each and every iteration, we wish to upload the foreign money code to the choice part and append the choice part to each the choose parts.
1 |
const end result = currencies.forEach((foreign money) => { |
2 |
|
3 |
const optionFrom = report.createElement("possibility"); |
4 |
optionFrom.classList.upload("select-option"); |
5 |
optionFrom.worth = foreign money.code; |
6 |
if (foreign money.code === "USD") { |
7 |
optionFrom.decided on = true; |
8 |
}
|
9 |
optionFrom.textual content =`${foreign money.flag} ${foreign money.code} - ${foreign money.title}`; |
10 |
|
11 |
fromCurrency.appendChild(optionFrom); |
12 |
|
13 |
const optionTO = report.createElement("possibility"); |
14 |
optionTO.classList.upload("select-option"); |
15 |
optionTO.worth = foreign money.code; |
16 |
if (foreign money.code === "EUR") { |
17 |
optionTO.decided on = true; |
18 |
}
|
19 |
optionTO.textual content =`${foreign money.flag} ${foreign money.code} - ${foreign money.title}`; |
20 |
toCurrency.appendChild(optionTO); |
21 |
});
|
Within the code above, we use the ForEach()
serve as to iterate on each and every the currencies array knowledge and do the next:
- Extracts the foreign money key from the currencies array for each and every foreign money
- will get the flag
- will get the foreign money title
- Creates an HTML possibility part for the “
fromCurrency
” choose dropdown . - units the choice worth to the foreign money code
- Units the choice textual content to a mixture of the flag, the foreign money title, and the foreign money code
- Appends the created possibility part to the “
fromCurrency
” choose dropdown. - Creates an alternative choice part for the “
toCurrency
” choose dropdown with the similar knowledge because thefromCurrency
- Appends the created possibility part to the “toCurrency” choose dropdown.
- In the end we invoke the
addCurrency()
serve as to use the capability.
The choice worth would be the foreign money code, and the choice textual content would be the foreign money flag, foreign money code, and foreign money title separated through a hyphen.
We additionally set the default foreign money within the fromCurrency
possibility part to USD and the default foreign money for the toCurrency
possibility part to EUR.
Now our drop down are appearing the currencies.



Code Refactoring
From the addCurrency()
serve as you’ll see that we’re repeating the similar code so as to add the choice values. Let’s create some other serve as for producing the choices for each and every foreign money part.
The serve as will appear to be this:
1 |
serve as createOption(nation, defaultCode, part ){ |
2 |
// console.log(nation);
|
3 |
const possibility = report.createElement("possibility"); |
4 |
possibility.classList.upload("select-option"); |
5 |
possibility.worth = nation.code; |
6 |
if (nation.code === defaultCode) { |
7 |
possibility.decided on = true; |
8 |
}
|
9 |
possibility.textual content = `${nation.flag} ${nation.code} - ${nation.title}`; |
10 |
part.appendChild(possibility); |
11 |
|
12 |
|
13 |
}
|
The createOption()
serve as takes 3 parameters: the rustic object, the default code, and the part the place the choices will probably be appended.
Subsequent, replace the addCurrency() serve as as follows:
1 |
serve as addCurrency() { |
2 |
const end result = nations.map((nation) => { |
3 |
createOption(nation, "USD", fromCurrency ); |
4 |
createOption(nation, "EUR", toCurrency ) |
5 |
|
6 |
});
|
7 |
}
|
The serve as is now more straightforward to learn since we don’t have any repetitive code.
Foreign money Conversion
We can use the ExchangeRate API for foreign money conversion. The ExchangeRate API supplies foreign money conversion charges for 161 currencies.
The API lets in builders to transform currencies through offering a couple of foreign money codes within the request. For instance, if you wish to convert USD to EUR, your API name will appear to be this:
1 |
https://v6.exchangerate-api.com/v6/24faec6b42da4a96ceea41d3/pair/USD/EUR |
The endpoint will give us the next end result.
1 |
{
|
2 |
"end result": "luck", |
3 |
"documentation": "https://www.exchangerate-api.com/medical doctors", |
4 |
"terms_of_use": "https://www.exchangerate-api.com/phrases", |
5 |
"time_last_update_unix": 1703721602,
|
6 |
"time_last_update_utc": "Thu, 28 Dec 2023 00:00:02 +0000", |
7 |
"time_next_update_unix": 1703808002,
|
8 |
"time_next_update_utc": "Fri, 29 Dec 2023 00:00:02 +0000", |
9 |
"base_code": "USD", |
10 |
"target_code": "EUR", |
11 |
"conversion_rate": 0.9015
|
12 |
}
|
Since we have already got the codes in our choose choices, we can cross the values within the API and multiply the conversion charge through the volume to get the end result.
Create a serve as referred to as convertCurrency()
serve as. Within the serve as:
- get the show part
- get the values from the chosen choices
- Retailer the url in a variable.
1 |
const BASE_URL = `https://v6.exchangerate-api.com/v6/${apiKey}`; |
2 |
const fromCurrrencyCode = report.getElementById("fromCurrency").worth; |
3 |
const toCurrencyCode = report.getElementById("toCurrency").worth; |
4 |
const end result = report.querySelector(".end result"); |
5 |
const error = report.querySelector(".error"); |
Be sure you provide your API key from the Trade Charge API. You’ll be able to download one totally free right here.
Within the convertCurrency()
serve as, we first take a look at if a sound quantity has been entered, and if true, we carry out a GET request to the change charge API with the foreign money pairs.
The reaction will comprise the conversion charge. In the end we replace the end result with a formatted transformed quantity
1 |
serve as convertCurrency() { |
2 |
const BASE_URL = `https://v6.exchangerate-api.com/v6/${apiKey}`; |
3 |
|
4 |
const fromCurrrencyCode = report.getElementById("fromCurrency").worth; |
5 |
const toCurrencyCode = report.getElementById("toCurrency").worth; |
6 |
const end result = report.querySelector(".end result"); |
7 |
const error = report.querySelector(".error"); |
8 |
|
9 |
console.log(fromCurrrencyCode); |
10 |
console.log(toCurrencyCode); |
11 |
|
12 |
const quantity = enter.worth; |
13 |
|
14 |
if (quantity !== "" && parseFloat(quantity) >= 1) { |
15 |
const url = `${BASE_URL}/pair/${fromCurrrencyCode}/${toCurrencyCode}`; |
16 |
console.log(url); |
17 |
fetch(url) |
18 |
.then((resp) => resp.json()) |
19 |
.then((knowledge) => { |
20 |
console.log(knowledge.conversion_rate); |
21 |
|
22 |
const conversionResult = (quantity * knowledge.conversion_rate).toFixed( |
23 |
2
|
24 |
);
|
25 |
const formattedResult = conversionResult.exchange( |
26 |
/B(?=(d{3})+(?!d))/g, |
27 |
"," |
28 |
);
|
29 |
|
30 |
end result.innerHTML = `${quantity} ${fromCurrrencyCode} = ${formattedResult} ${toCurrencyCode}`; |
31 |
quantity.innerHTML = " "; |
32 |
})
|
33 |
.catch(() => { |
34 |
error.textContent = "An error occured, please check out once more later "; |
35 |
});
|
36 |
} else { |
37 |
alert("Please input an quantity"); |
38 |
}
|
39 |
}
|
If an error happens, we show a message to the consumer, permitting them to know one thing went incorrect.
For the conversion to paintings, let’s upload an tournament listener to the convert button and invoke the convertCurrency()
serve as, as proven under.
1 |
const convertBtn = report.querySelector(".convert"); |
2 |
convertBtn.addEventListener("click on", () => { |
3 |
convertCurrency(); |
4 |
});
|
Ultimate Consequence
This is the general end result!
Conclusion
This educational has coated the best way to construct a foreign money converter that fetches real-time knowledge from the Trade Charge API. Be sure you get your unfastened API key from the ExchangeRateAPI, and feature a laugh construction issues!
[ad_2]