Build a simple currency converter with HTML ,CSS & JavaScript
Published: 2022-09-04 11:12:22

We’ll be building a simple currency converter with HTML and JavaScript and after which design it using CSS. We’ll be using exchangerate-api.com to fetch the real time currency prices so its advisable before getting started you need to create yourself a free account to get your API key.

We'll get started by creating the required HTML markup. We’ll need a form so users can enter the amount and the currencies they would like to convert. There’s also a paragraph that will be used to output the result of the converted currency:

``<form action="#">
      <p>Enter Amount</p>
        <input id="amount" type="number" value="1" />
        <p>From</p>
        <div class="select-box">
        <select id="from" class="input"></select>
          </div>
        <p>To</p>
        <div class="select-box">
        <select id="to" class="input"></select>
          </div>   
          <p id="result" class="result-rate">
            <span id="txt-from"></span>
            <span id="txt-to"></span>
          </p>
          <div>
        <input id="btn-convert" class="button0" type="button" value="Convert" /> 
        </div>
    </form>``
As you can see we have a form with..

- an input named from_amount
- a selectbox named from_currency and one named to_currency
- a paragraph tag with the class of to_amount

You may have noticed that the <select> element doesn’t contain any <options>. We’ll populate this dynamically from the JavaScript. This will ensure both lists remain the same if currencies are added or removed and is just easier to maintain in general.

If you open up money.js, you will see that Wes has already given us just a list of currencies, which is the currency code translated to their English version.

Here is what the currencies Object looks like:

``const currencies = {
  AUD: "Australian Dollar",
  CAD: "Canadian Dollar",
  EUR: "Euro",
  GBP: "British Pound",
  INR: "Indian Rupee",
  JPN: "Japanese Yen",
  USD: "United States Dollar",
  ZAR: "South African Rand",
};``
Code language: JavaScript (javascript)
There’s many more supported currencies but this is enough for this exercise.

Let's start by converting those currencies so we can populate them.We'll’ populate the <select> elements using innerHTML:

`const fromCurrency = document.getElementById("from");
const toCurrency = document.getElementById("to");
fromCurrency.innerHTML = getOptions(currencies);
toCurrency.innerHTML = getOptions(currencies);`
Code language: JavaScript (javascript)

After the currencies object, make a function called generateOptions which will accept one parameter, options, which will be an object.The HTML generated with the getOptions function that looks like this:

``function getOptions(data) {
  return Object.entries(data)
    .map(([country, currency]) => `<option value="${country}">${country} | ${currency}</option>`)
    .join("");
}``
Code language: JavaScript (javascript)
This loops through the currencies Object and generates the <option> elements:

Next we’ll add an eventListener to detect when the button is clicked using the following line of code:

``document.getElementById("btn-convert").addEventListener("click", fetchCurrencies);``
Code language: JavaScript (javascript)

This calls a fetchCurrencies function on click that looks like this:

``function fetchCurrencies() {
  const from = fromCurrency.value;
  const to = toCurrency.value;
  const amount = document.getElementById("amount").value;
  // Important: Include your API key below
  fetch("https://v6.exchangerate-api.com/v6/your obtained keys/latest/" + primary)
    .then((response) => {
      if (response.ok) {
        return response.json();
      } 
    })
    .then((data) => {
      console.log(data);
      displayCurrency(data, from, to, amount);
    })
    .catch((error) => console.error("FETCH ERROR:", error));
}``
Code language: JavaScript (javascript)
Here we’ve used the fetch method to make the API request of the from currency selected. If the request was successful we then pass the data to a displayCurrency function that looks like this:

``function displayCurrency(data, from, to, amount) {
  const calculated = amount * data.conversion_rates[to];
  document.getElementById("result").setAttribute("style", "display:block");
  document.getElementById("txt-from").innerText = amount + " " + from + " = ";
  document.getElementById("txt-to").innerText = calculated + " " + to;
}``
Code language: JavaScript (javascript)
This function multiples the amount that was entered into the form by the converted to currency. We then reveal the hidden result <p> and populate it with the converted currency text.

Up to this point, we should have a working currency calculator that can be used as it is or modified to suit other currency conversions tasks within a website or application. 

From here, create a style.css document to connect it to the html document.In the style.css, we can use the   following code to style our body:

`body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #675AFE;
}`
After which we can wrapp the form this way:

`.wrapper header{
  font-size: 28px;
  font-weight: 500;
  text-align: center;
}
.wrapper form{
  margin: 40px 0 20px 0;
}`

You can later style the buttons ,add a background image and many other more through application of various styles in the style.css file.