Creating a Currency Converter with pure JS with exchangerate api
Tags: javascript, codenewbie, api, 100daysofcode
Published: 2021-04-03 10:29:40

1. Fetch the exchange rate from internet(with the help of [exchangerateapi](https://exchangeratesapi.io/))

# **Setting up HTML and CSS**

I set my page for a three column three row layout with [css grid](https://css-tricks.com/snippets/css/complete-guide-grid/) and warapped all the page inside a container div.

```jsx
display: grid;
grid-template:
    "title title title" minmax(min-content, 5rem)
    ". content ." minmax(100px, auto)
    "footer footer footer" minmax(2.5rem, max-content)
        / minmax(20px, 1fr) 5fr minmax(20px, 1fr);
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng6ewc9vvmnfgro3ni1m.png) 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9s71d0cz2q6ma07153i7.png)
 

Inside the content I decided to have two panes(divs) sliding, I got this Idea from a challenge given by scrimba : **Day 15** of JavaScriptmas : [JavaScript Carousel](https://scrimba.com/learn/adventcalendar/-javascript-challenge-carousel-c9r874s3) ([my solution](https://scrimba.com/scrim/co8f74b6fb3c3af1ded23ed23)). Basically what it does is using one div we declare ***viewing area***, another div holds all the divs inside it side by side, and we use css transforms with transitions for the movement of the ***windows container*** with animations.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfo0085179xz2hoqo96n.png)
 
I split the input boxes and button in two parts. These two parts are placed in two separate divs. In the first one it gets 2 currencies to convert from x_currency to y_currency. In the 2nd part it had a input box to enter the amount of x_currency to be converted to y_currency using a Exchange rate form another input box.

The viewing div has css property `overflow : hidden` and the windows container(I called it `slider`) is constucted with again, css grid to have only one row.

```css
.slider {
  width: 100%;
  transform-style: preserve-3d;
  display: grid;
  grid-template-columns: repeat(2, 100%);
  transform: translateX(0);
  transition: transform 450ms;
}
```

# **Making Interactive with JavaScript**

To slide between the windows I built a function which will get the **width** to the current viewing window(div) and `transform = translateX(width)` and to get back to previous div it will just do `translateX(0)`. I made a function to do just that:

```jsx
// animating between two divs
// `true` for backward animation
// `false` for forward animation
const animateSlider = (isPositive) => {
  // dynamically getting the length to translate
  let to_translate = sliding.offsetWidth;if (isPositive) {
    slider.style.transform = `translate(0px)`;
  } else {
    slider.style.transform = `translate(${-to_translate}px)`;
  }
};
```

My page only have 2 divs sliding and to switch between I was using it on a `button click` event and `key press` event.

```jsx
//for click event listners
document.getElementById("id").addEventListener("click", functionToExecute)// for key event listners
document.getElementById("id").addEventListener("keyup",(event) => {
    if (event.key == "Enter") {
        functionToExecute();
    }
});
```

# **Fetching Currency Info from exchangerate api**

[Exchange rates API](https://exchangeratesapi.io/) is a free service for current and historical foreign exchange rates published by the [European Central Bank](https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html). Using it with `fetch` the JavaScript loads the supported currencies into two lists(datalist and array), one for UI suggestion in the text box and other to verify that if our page will be able to translate the source currency to target currency, if not user will be offered to enter custom exchange rate for that unsupported currency and if found the input box for Exchange rate will be grayed out and made read-only.

```jsx
// gets exchange rate for specific currenciesconst getExRate = async (frm, to) => {
    let req_url = `https://api.exchangeratesapi.io/latest?base=${frm}&symbols=${to}`;
    let res = await fetch(req_url);
    let data = await res.json();
    return data.rates[to];
};
```

```jsx
// this func will load all supported currencies into a datalist
// and in an array for some logical operation later
const loadSupporedCurrencies = async () => {
  //   reseting all the inputbox values
  ex_rate_box.value = "";
  source_amount_box.value = "";
  source_amount_box.value = "";
  target_currency_box.value = "";//   getting all the supported currencies from `exchangeratesapi`
  let response = await fetch("https://api.exchangeratesapi.io/latest");
  let data = await response.json();//   adding the base currency to the list
  addListEntry(data.base, data.base);
  curr_list.push(data.base);// Read currencies as key from the json obj and pushing into the list
  for (let key in data.rates) {
    addListEntry(key, key);
    curr_list.push(key);
  }
};
```

[https://codepen.io/saoud-the-scripter/pen/xxgdLEp](https://codepen.io/saoud-the-scripter/pen/xxgdLEp)