How to Make Currency Converter Using HTML CSS & JavaScript

A currency converter is a useful tool that allows users to convert between different currencies at current exchange rates. In this step-by-step tutorial you will learn how to create a simple currency converter using HTML, CSS, and JavaScript that fetches exchange rates from a free API and provides real-time currency conversion.

Steps to Create Currency Converter Using HTML, CSS & JS

Before we start, ensure you have the following:

  • Basic knowledge of HTML, CSS, JavaScript and API.
  • A code editor (e.g., Visual Studio Code, Sublime Text).
  • A stable internet connection (to fetch exchange rate data from an API).

Folder structure of this project:

currency-converter/
├── index.html
├── style.css
└── script.js

Step 1: Create HTML Structure for the Currency Converter

First, create the HTML structure for your currency converter. In the html code you’ll need two elements to choose the source and target currencies, two input fields to enter the amount and display the result, and two buttons one for trigger the conversion and another for swapping the currencies.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Currency Converter</title>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <h1>Currency Converter</h1>
        <div class="converter">
            <div class="input-group">
                <input type="number" id="amount" placeholder="Enter amount" />
                <select id="fromCurrency">
                    <option value="">Select From Currency</option>
                </select>
            </div>
            <div><strong>To</strong></div>
            <div class="input-group">
                <input type="text" id="result" placeholder="Result" disabled />
                <select id="toCurrency">
                    <option value="">Select Currency To</option>
                </select>
            </div>
            <button id="convert">Convert</button>
            <button id="swap">Swap</button>
        </div>
        <script src="script.js"></script>
    </body>
</html>

Step 2: Add CSS Styles to the HTML Structure

Here is the CSS code for the structure of the index.html. put the following code into the style.css file:

*,
*::after,
*::before {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f2f2f2;
}

h1 {
    color: #222;
}

.converter {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    display: inline-block;
}

.input-group {
    margin: 10px 0;
}

input[type="number"],
input[type="text"],
select,
button {
    padding: 10px;
    width: 100%;
    border: 1px solid #ccc;
    border-radius: 3px;
    font-size: 16px;
    outline: none;
}
button {
    cursor: pointer;
    background-image: linear-gradient(#f7f8fa, #e7e9ec);
    border-color: #adb1b8 #a2a6ac #8d9096;
}

#swap {
    margin-top: 10px;
}

After adding the CSS the currency converter will look like the following image. I know its not cool but the styling is important in this project. If you don’t like style according yours.

currency converter

Step 3: Fetch Currency Exchange Rates & Apply using JavaScript

To fetch exchange rates, you’ll need an API that provides currency conversion data. In this example, we’ll use the Free Currency Rates API (by Fawaz Ahmed) to get exchange rate data. It is Free and you don’t need to Sign up or an API key.

Features of this Free Currency Rates API:

  • Free & Blazing Fast response
  • No Rate limits
  • 150+ Currencies, Including Common Cryptocurrencies
  • Daily Updated
# Lists all the available currencies in prettified json format:
https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.json

# Get a minified version of it:
https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.min.json
# Get the currency list with fromCurrency as base currency
https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{fromCurrency}.json

Now, create a script.js file and add the following JavaScript code to fetch exchange rates and populate the currency dropdowns. Read the code comments to understand the code.

const fromCurrency = document.getElementById("fromCurrency"); // From Currency Select Element
const toCurrency = document.getElementById("toCurrency"); // To Currency Select Element
const amount = document.getElementById("amount"); // From Currency Input Element
const result = document.getElementById("result"); // To Currency Input Element
const convert = document.getElementById("convert"); // Convert Button
const swap = document.getElementById("swap"); // Swap Button

// Variables
let fromCurrencyValue;
let toCurrencyValue;
const fromCurrencyRate = 1; // This Rate will Get From API
let toCurrencyRate = null; // Currency rate

/**
 * Convert currency based on rates fetched from API.
 */
function convertCurrency() {
    if (toCurrencyRate === null || isNaN(parseFloat(amount.value)))
        return;
    const convertedAmount =
        parseFloat(amount.value) * toCurrencyRate;
    result.value = convertedAmount.toFixed(2);
}

// API URL for currency list
const currencyListAPI_URL =
    "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.min.json";

// Fetching currency list
fetch(currencyListAPI_URL)
    .then((response) => response.json())
    .then((data) => {
        // Inserting currency list into select elements
        for (i in data) {
            const option1 = new Option(data[i], i);
            const option2 = new Option(data[i], i);
            fromCurrency.add(option1);
            toCurrency.add(option2);
        }
    });

// Fetching currency information
async function fetchCurrenciesInfo() {
    if (!fromCurrencyValue || !toCurrencyValue) return;

    // Disabling buttons and changing text
    convert.disabled = true;
    swap.disabled = true;
    convert.innerText = "Fetching...";

    const apiUrl = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${fromCurrencyValue}.min.json`;
    try {
        const data = await (await fetch(apiUrl)).json();
        toCurrencyRate = parseFloat(
            data[fromCurrencyValue][toCurrencyValue]
        );

        if (toCurrencyRate <= 0 || isNaN(toCurrencyRate)) {
            toCurrencyRate = null;
            alert("Currency Rate not found in the Response JSON.");
        }
    } catch (err) {
        toCurrencyRate = null;
        console.log(err.message);
    } finally {
        // Re-enable buttons and reset text
        convert.innerText = "Convert";
        convert.disabled = false;
        swap.disabled = false;
    }
}

// Handle select change
const onSelectChange = (e, fromCurrency = true) => {
    e.target.disabled = true;
    e.target.disabled = false;

    const value = e.target.value;
    if (fromCurrency) {
        fromCurrencyValue = value;
    } else {
        toCurrencyValue = value;
    }
    fetchCurrenciesInfo();
};

// Event listeners
fromCurrency.addEventListener("change", (e) => onSelectChange(e));
toCurrency.addEventListener("change", (e) =>
    onSelectChange(e, false)
);
convert.addEventListener("click", convertCurrency);
swap.addEventListener("click", () => {
    if (!toCurrencyValue || !fromCurrencyValue) return;

    // Swap currency values
    [toCurrencyValue, fromCurrencyValue] = [
        fromCurrencyValue,
        toCurrencyValue,
    ];
    fromCurrency.value = fromCurrencyValue;
    toCurrency.value = toCurrencyValue;

    // Swap amount values
    [amount.value, result.value] = [result.value, amount.value];

    // Swap currency rates
    toCurrencyRate = fromCurrencyRate / toCurrencyRate;
    convertCurrency();
});

Step 4: Test Your Currency Converter

  • Now, open the HTML file in your web browser, and you should see your currency converter interface.
  • Select source and target currencies, enter an amount, and click the “Convert” button.
  • The converted amount will be displayed in the result field.

Congratulations! You’ve created a simple JavaScript currency converter that fetches real-time exchange rates from an API. You can further enhance this project by adding more features like currency symbols, currency flags, and error handling for invalid inputs.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy