Photo by Jason Leung on Unsplash

Creating a Currency Converter with pure JS with exchangerate api

Kuntal Das

--

I will show how to build a currency converter with these following features:

  1. Huge range of Currencies can be converted
  2. Fetch the exchange rate from internet(with the help of exchangerateapi)
  3. Give users freedom to enter exchange if it is not in our list.
  4. Making a cool animation. 😍

[UPDATE: recently I came to know my implementation is not working because the API is no longer open to all like before. Now it needs an API-Key to query the API. I’ll update the post as soon as I get time to adapt my code to their specifications.]

So Where to Start ?

I started in my favorite code editor VS Code by creating a index.html in a separate empty folder and added index.js and index.css Or You can just go with codepen and click on pen to get started.

Setting up HTML and CSS

I set my page for a three column three row layout with css grid and warapped all the page inside a container div.

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);

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 (my solution). 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.

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.

.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:

// 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.

//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 is a free service for current and historical foreign exchange rates published by the European Central Bank. 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.

// 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];
};

Okey now can convert, but how you got all the currencies and made it usable for the user ?

Well I did set up the page such a way it can call the api and it loades up a list which is used for logical checking in JS and a datalist to let users suggest in the inputbox. I made this thing a function too 😅

// 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);
}
};

With addition of some more basic validations my currency converter is complete !

This was made for “Weekly Web Dev Challenge” at Scrimba on 13th Jan 2021 : Currency Converter : my solution on scrimba.

--

--

Kuntal Das
Kuntal Das

Written by Kuntal Das

who loves to learn new things

No responses yet