Create a Currency Converter with HTML, CSS, and Vanilla JavaScript

Trending 3 months ago

Let’s create a afloat functional rate converter exertion utilizing HTML, CSS, and vanilla JavaScript. By nan extremity of this tutorial, we will person a responsive rate app that fetches real-time information pinch nan Exchange Rate API and presents it successful a user-friendly interface.

HTML Structure

Our rate exertion will person a elemental interface containing :

  • An input section for nan magnitude to beryllium converted.
  • A drop-down to prime nan from Currency value
  • A 2nd drop-down to prime nan to rate value
  • A person button
  • A <p> tag to show nan converted amount
  • A <p> tag to show immoderate errors that mightiness hap during nan conversion process.

The HTML code  will look for illustration this:

1 <div class="container">
2
3 <div class="currency-container">
4 <h1>Currency converter</h1>
5 <div class="input-box">
6 <label for="amount">Enter amount</label>
7 <input type="text" id="amount" placeholder="100" required/>
8 </div>
9 <div class="currency">
10 <div class="box">
11 <select
12 class="select-option"
13 name="from-currency"
14 id="fromCurrency"
15 >
16 <option value="USD">United States Dollar</option>
17 </select>
18 </div>
19 <div>
20 <span>TO</span>
21 </div>
22 <div class="box">
23 <select class="select-option" name="to-currency" id="toCurrency">
24 <option value="USD">United States Dollar</option>
25 </select>
26 </div>
27 <button class="convert">Convert</button>
28 <p class="result"></p>
29 <p class="error"></p>
30
31 </div>
32 </div>
33 </div>

Currently, we are utilizing nan action worth arsenic a placeholder. We will switch and adhd much action information dynamically pinch JavaScript.

Styling With CSS

Let’s commencement pinch immoderate basal styles. We’ve pulled successful nan alternatively fantabulous Bricolage Grotesque font from Google fonts too:

1 * {
2 margin: 0;
3 padding: 0;
4 box-sizing: border-box;
5 font-family: 'Bricolage Grotesque', sans-serif;
6 }
7
8 h1 {
9 font-size: 5em;
10 font-weight: bold;
11 text-align: center;
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 color: #040203;
22 display: flex;
23 flex-direction: column;
24 align-items: center;
25 justify-content: center;
26 }
27
28 .currency-container {
29 height: fit-content;
30 background-color: #7cb889;
31 padding: 3em;
32 border-radius: 40px;
33 }

For nan input and explanation (including nan placeholder successful nan input) they will person nan pursuing styles:

1 .input-box {
2 display: flex;
3 flex-direction: column;
4 align-items: center;
5 justify-content: center;
6 text-align: center;
7 }
8
9 label {
10 font-size: 1.5em;
11 margin-bottom: .4em;
12 }
13
14 #amount {
15 width: 300px;
16 padding: 20px;
17 border-radius: 30px;
18 font-size: 3em;
19 border: 3px solid black;
20 background: transparent;
21 color: black;
22
23 }
24 #amount:focus {
25 border: 3px solid white;
26 outline: none;
27 }
28
29 ::placeholder {
30 color: rgba(0,0,0,0.6);
31 opacity: 1; /* Firefox */
32 }

Next, we will use styling to nan container elements containing nan From and To rate drop-downs. The drop-down elements will beryllium arranged successful a file layout utilizing Flexbox and centered vertically and horizontally. We besides person a spread betwixt nan container elements, immoderate padding, and a separator radius.

1 .currency {
2 margin-top: 50px;
3 padding: 20px 20px;
4 display: flex;
5 align-items: center;
6 justify-content: center;
7 flex-direction: column;
8 gap: 1.5rem;
9 }
10
11 .box {
12 display: flex;
13 align-items: center;
14 justify-content: center;
15 }

 The select-option will person nan pursuing styles

1 .select-option {
2 font-size: 16px;
3 color: #333;
4 padding: 20px;
5 display: block;
6 font-weight: 700;
7 line-height: 1.3;
8 width: 100%;
9 max-width: 100%;
10 margin: 0;
11 outline: none;
12 border-radius: 20px;
13 border: 3px solid black;
14 }

Finally, nan person button, nan result, and nan correction connection elements will person nan pursuing styles:

1 button {
2 width: 100%;
3 height: 100px;
4 padding: 10px;
5 border-radius: 30px;
6 border: none;
7 font-size: 1.5em;
8 align-items: center;
9 background-color: black;
10 color: #fff;
11 margin-top: 30px;
12 }
13 .result {
14 color: black;
15 font-size: 2.5em;
16 }
17 .error {
18 color: #800020;
19 font-size: 12px;
20 }

JavaScript Functionality

The JavaScript functionality will person 2 parts:

  • Getting nan rate code, rate name, and emblem from nan REST countries API
  • getting conversion complaint from nan Exchange Rate API

REST Countries API

The REST countries API provides an API pinch nan endpoint https://restcountries.com/v3.1/all wherever you tin select results by providing nan fields you are willing in. In our case, we want nan state flag, rate name, and rate codification and nan endpoint will look for illustration this:

1 https://restcountries.com/v3.1/all?fields=currencies,flag

The resulting sample information will look for illustration this:

1 {
2 "name": {
3 "common": "Eritrea",
4 "official": "State of Eritrea",
5 "nativeName": {
6 "ara": {
7 "official": "دولة إرتريا",
8 "common": "إرتريا‎"
9 },
10 "eng": {
11 "official": "State of Eritrea",
12 "common": "Eritrea"
13 },
14 "tir": {
15 "official": "ሃገረ ኤርትራ",
16 "common": "ኤርትራ"
17 }
18 }
19 },
20 "currencies": {
21 "ERN": {
22 "name": "Eritrean nakfa",
23 "symbol": "Nfk"
24 }
25 },
26 "flag": "🇪🇷"
27 },

To make it easier to show our currencies, we will fetch nan information and shop it successful a JavaScript file. The book for fetching nan information will look for illustration this:

1 const url =
2 "https://restcountries.com/v3.1/all?fields=name,currencies,flag";
3 fetch(url)
4 .then((response) => response.json())
5 .then((data) => {
6
7 const result = [];
8 data.forEach((country) => {
9 if (Object.keys(country.currencies).length >0) {
10 result.push({
11 countryname: country.name.common,
12 name: Object.values(country.currencies)[0].name,
13 code: Object.keys(country.currencies)[0],
14 flag: country.flag,
15 });
16 }
17 });
18
19 result.sort((a, b) => a.code.localeCompare(b.code));
20 const jsonString = JSON.stringify(result, null);
21 console.log(jsonString);
22
23 });

The codification supra does nan following:

  • We usage nan fetch() method to make an HTTP petition to nan REST countries API.
  • Then, we person nan consequence to JSON format and commencement processing nan data.
  • From nan consequence JSON, we first cheque if each state has a rate codification since not each countries person a rate code.
  • If a state has a currency, we create an entity pinch its name, code, and rate sanction and push it to nan quiet consequence array.
  • Then we benignant nan rate codification alphabetically.
  • Finally, we person nan consequence to JSON and people nan stringified information to nan console.

When you tally nan book successful a browser environment, you should beryllium capable to transcript nan information to your JavaScript file. The information looks for illustration this:

Alternatively, adhd this link to your book utilizing nan src attribute.

Next, let’s get nan prime elements.

1 let fromCurrency = document.getElementById("fromCurrency");
2 let toCurrency = document.getElementById("toCurrency");

Since we person nan information successful an array, it’s now easier to append nan currencies to nan action elements of nan fromCurrency and toCurrency prime elements.

Create a usability called addCurrency(). Inside nan addCurrency() function, we usage nan forEach() usability to loop done nan currencies array; for each iteration, we want to adhd nan rate codification to nan action constituent and append nan action constituent to some nan prime elements.

1 const result = currencies.forEach((currency) => {
2
3 const optionFrom = document.createElement("option");
4 optionFrom.classList.add("select-option");
5 optionFrom.value = currency.code;
6 if (currency.code === "USD") {
7 optionFrom.selected = true;
8 }
9 optionFrom.text =`${currency.flag} ${currency.code} - ${currency.name}`;
10
11 fromCurrency.appendChild(optionFrom);
12
13 const optionTO = document.createElement("option");
14 optionTO.classList.add("select-option");
15 optionTO.value = currency.code;
16 if (currency.code === "EUR") {
17 optionTO.selected = true;
18 }
19 optionTO.text =`${currency.flag} ${currency.code} - ${currency.name}`;
20 toCurrency.appendChild(optionTO);
21 });

In nan codification above, we usage nan ForEach() usability to iterate connected each nan currencies array information and do nan following:

  • Extracts nan rate cardinal from nan currencies array  for each currency
  • gets nan flag
  • gets nan rate name
  • Creates an HTML action constituent for nan "fromCurrency" prime dropdown  . 
  • sets nan action worth to nan rate code
  • Sets nan action matter to a operation of nan flag, nan rate name, and nan rate code
  • Appends nan created action constituent to nan "fromCurrency" prime dropdown.
  • Creates different action constituent for nan "toCurrency" prime dropdown pinch nan aforesaid information arsenic nan fromCurrency
  • Appends nan created action constituent to nan "toCurrency" prime dropdown.
  • Finally we invoke nan addCurrency() usability to use nan functionality.

The action worth will beryllium nan rate code, and nan action matter will beryllium nan rate flag, rate code, and rate sanction separated by a hyphen.

We besides group nan default rate successful nan fromCurrency action constituent to USD and nan default rate for nan toCurrency action constituent to EUR.

Now our driblet down are showing nan currencies.

Code Refactoring

From nan addCurrency() usability you tin spot that we are repeating nan aforesaid codification to adhd nan action values. Let’s create different usability for generating nan options for each rate element.

The usability will look for illustration this:

1 function createOption(country, defaultCode, element ){
2 // console.log(country);
3 const option = document.createElement("option");
4 option.classList.add("select-option");
5 option.value = country.code;
6 if (country.code === defaultCode) {
7 option.selected = true;
8 }
9 option.text = `${country.flag} ${country.code} - ${country.name}`;
10 element.appendChild(option);
11
12
13 }

The createOption() usability takes 3 parameters: nan state object, nan default code, and nan constituent wherever nan options will beryllium appended.  

Next, update nan addCurrency() usability arsenic follows:

1 function addCurrency() {
2 const result = countries.map((country) => {
3 createOption(country, "USD", fromCurrency );
4 createOption(country, "EUR", toCurrency )
5
6 });
7 }

The usability is now easier to publication since we don’t person immoderate repetitive code.

Currency Conversion

We will usage nan ExchangeRate API for rate conversion. The ExchangeRate API  provides rate conversion rates for 161 currencies.

The API allows developers to person currencies by providing a brace of rate codes successful nan request. For example, if you want to person USD to EUR, your API telephone will look for illustration this:

1 https://v6.exchangerate-api.com/v6/24faec6b42da4a96ceea41d3/pair/USD/EUR

The endpoint will springiness america nan pursuing result.

1 {
2 "result": "success",
3 "documentation": "https://www.exchangerate-api.com/docs",
4 "terms_of_use": "https://www.exchangerate-api.com/terms",
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 already person nan codes successful our prime options, we will walk nan values successful nan API and multiply nan conversion complaint by nan magnitude to get nan result. 

Create a usability called convertCurrency() function. In nan function:

  • get nan show element
  • get nan values from nan selected options
  • Store nan url successful a variable.
1 const BASE_URL = `https://v6.exchangerate-api.com/v6/${apiKey}`;
2 const fromCurrrencyCode = document.getElementById("fromCurrency").value;
3 const toCurrencyCode = document.getElementById("toCurrency").value;
4 const result = document.querySelector(".result");
5 const error = document.querySelector(".error");

Ensure you proviso your API cardinal from nan Exchange Rate API. You tin get 1 for free here.

In nan convertCurrency() function, we first cheque if a valid magnitude has been entered, and if true, we execute a GET petition to nan speech complaint API pinch nan rate pairs.

The consequence will incorporate nan conversion rate. Finally we update nan consequence pinch a formatted converted amount

1 function convertCurrency() {
2 const BASE_URL = `https://v6.exchangerate-api.com/v6/${apiKey}`;
3
4 const fromCurrrencyCode = document.getElementById("fromCurrency").value;
5 const toCurrencyCode = document.getElementById("toCurrency").value;
6 const result = document.querySelector(".result");
7 const error = document.querySelector(".error");
8
9 console.log(fromCurrrencyCode);
10 console.log(toCurrencyCode);
11
12 const amount = input.value;
13
14 if (amount !== "" && parseFloat(amount) >= 1) {
15 const url = `${BASE_URL}/pair/${fromCurrrencyCode}/${toCurrencyCode}`;
16 console.log(url);
17 fetch(url)
18 .then((resp) => resp.json())
19 .then((data) => {
20 console.log(data.conversion_rate);
21
22 const conversionResult = (amount * data.conversion_rate).toFixed(
23 2
24 );
25 const formattedResult = conversionResult.replace(
26 /\B(?=(\d{3})+(?!\d))/g,
27 ","
28 );
29
30 result.innerHTML = `${amount} ${fromCurrrencyCode} = ${formattedResult} ${toCurrencyCode}`;
31 amount.innerHTML = " ";
32 })
33 .catch(() => {
34 error.textContent = "An correction occured, please effort again later ";
35 });
36 } else {
37 alert("Please participate an amount");
38 }
39 }

If an correction occurs, we show a connection to nan user, letting them cognize thing went wrong. 

For nan conversion to work, let’s adhd an arena listener to nan person fastener and invoke nan convertCurrency() function, arsenic shown below.

1 const convertBtn = document.querySelector(".convert");
2 convertBtn.addEventListener("click", () => {
3 convertCurrency();
4 });

Final Result

Here is nan last result!

Conclusion

This tutorial has covered really to build a rate converter that fetches real-time information from nan Exchange Rate API. Ensure you get your free API cardinal from nan ExchangeRateAPI, and person nosy building things!

More
Source Tuts Plus
Tuts Plus