Building a Currency Converter in JavaScript

Introduction

In this article, we build a currency converter in JavaScript, with the help of our JavaScript package, which handles the requests to the API itself.

Furthermore, we will use vite as build tool and tailwind for easy styling.

Currency Converter Preview of the final outcome of this tutorial

Prerequisites

Scaffold your vite project

Navigate to your workspace on your machine where you want to create your currency converter project and initialize a new vite project:

Request

npm create vite@latest

Then follow the prompts in your console. Make sure to select vanilla for your project setup!

Afterward, switch to the newly created project folder.

Install the CurrencyAPI package

As mentioned above, we will use our JavaScript package:

Request

npm install --save @everapi/currencyapi-js

Install & configure tailwind.css (optional)

We want to use Tailwind CSS v3, so add it to your project together with postcss and autoprefixer for a clean and stable build process:

Request

npm install -D tailwindcss postcss autoprefixer

Afterward, initialize tailwind, which will create a tailwind.config.js in your project's root directory:

npx tailwindcss init

Open the newly created tailwind.config.js and modify the content attribute to match the vite setup:

module.exports = {
  content: [".*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

Also, add the Tailwind directives to your CSS:

@tailwind base;
@tailwind components;
@tailwind utilities;

As a last step, we need to tell postcss to include both tailwind and autoprefixer. Otherwise, the tailwind classes won't end up in our final css. To do so, create a file named postcss.config.js in your project root directory next to your tailwind config and add the following lines:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
}

Start vite in dev mode

Now that our preparations are done, we can start up vite:

Request

npm run dev

This should open up a new tab in your browser automatically. If not, open http://localhost:3000/.

You should now see the default Vite index page reading Hello Vite!.

Prepare your HTML

The next step is to adapt the default landing page.

Open the index.html and build a form for currency conversion. We will need:

  • A wrapper <form id="latest_rates_form"> for our inputs
  • An <input id="base_currency_input"> for the base currency
  • An <input id="currencies"> for the target currencies
  • A submit <button type="submit">
  • A container <div id="latest_rates_display"> where we display our dynamic currency data
<body class="bg-gradient-to-b from-cyan-800 to-slate-800 min-h-screen py-5">
    <form
        id="latest_rates_form"
        class="mx-auto w-full max-w-sm bg-white shadow rounded-md p-5 space-y-3 text-sm"
    >
        <div class="flex items-center justify-between space-x-5">
            <label for="base_currency_input">Base currency:</label>
            <input
                type="text"
                id="base_currency_input"
                name="base_currency"
                value="USD"
                class="border-slate-300 border rounded-md py-2 px-4 text-sm"
            />
        </div>
        <div class="flex items-center justify-between space-x-5">
            <label for="currencies">Target currencies:</label>
            <input
                type="text"
                id="currencies"
                name="currencies"
                value="EUR,CAD"
                class="border-slate-300 border rounded-md py-2 px-4 text-sm"
            />
        </div>
        <button
            type="submit"
            class="bg-slate-800 text-white rounded-md py-2 px-4 mx-auto relative block"
        >Get Latest Rates</button>
    </form>
    <div
        id="latest_rates_display"
        class="mx-auto my-5 w-full max-w-sm bg-white shadow rounded-md px-5 py-3 text-sm empty:hidden divide-y divide-dotted divide-slate-300"
    ></div>
    <script type="module" src="./main.js"></script>
</body>

Note that all CSS classes are tailwind specific, so if you want to use another CSS framework or style it yourself, feel free to remove them completely.

We will use the id attributes in our JavaScript.

Handle form submission in JavaScript

Now that our HTML structure is prepared, we can add the JavaScript functionality to call the CurrencyAPI. To do so, we need to open the main.js.

:::tip As this file is not empty, feel free to remove any code but keep the style import in the first line. :::

First we need to import the CurrencyAPI helper class from the JavaScript package:

import CurrencyAPI from '@everapi/currencyapi-js';

Now that we imported the Class, we also need to initialize a new instance using your API Key:

const currencyApi = new CurrencyAPI('YOUR_API_KEY_GOES_HERE');

Next, we store our HTML elements to constants so we can access them easily at a later point:

const latestRatesForm = document.getElementById('latest_rates_form');
const baseCurrencyInput = document.getElementById('base_currency_input');
const currenciesInput = document.getElementById('currencies');
const latestRatesDisplay = document.getElementById('latest_rates_display');

All that is left to do is to append a listener for the form submission, which will make a request to the API using the latest endpoint:

latestRatesForm.addEventListener('submit', (e) => {
    e.preventDefault();

    currencyApi.latest({
        base_currency: baseCurrencyInput.value.trim(),
        currencies: currenciesInput.value.replaceAll(' ', '')
    }).then(response => {
        let currencies = Object.keys(response.data);
        let resultHTML = '';

        for (let currency of currencies) {
            resultHTML += `<div class="flex items-center justify-between py-2">
                <strong>${currency}:</strong>
                <span>${response.data[currency].value}</span>
            </div>`;
        }
        latestRatesDisplay.innerHTML = resultHTML;
    });
});

That's it! You have successfully built a currency converter in JavaScript. When you now press the submit button, a request to the latest endpoint will be triggered.

If you have specified any target currencies, only those will be rendered. Otherwise, all supported currencies will be displayed.