[Project] Create a Currency Converter: A Step-by-Step Guide Using HTML, CSS, and JavaScript

By RoboSuperior・ Published in October 18, 20247.16 min read

Currency Converter Using HTML, CSS, and JavaScript

In this tutorial, we will create a Currency Converter Website using HTML, CSS, and JavaScript. We will build and use this Currency Conversion API to gather the latest real-time conversion rates. The objective is to understand how HTML, CSS, and JavaScript can be used along with this currency converter API to build this website.

What you'll build?

By the end of this tutorial, you will build an app that will look something like this:

Prerequisites

Visual Studio Code: I am using VS Code to write code. You can choose the editor of your choice Live Server Extension: I will also use an Extension for VSCode which is called “Live Server”. The live server enables you to open an HTML document, and it runs a server for you and opens a browser window with live refresh making it convenient for you to see live changes while development. Currency Conversion API: This is the free API we will be using to fetch currency details. If you plan to upgrade later, you can signup for an account here for maximum discounts

Installing VS Code

Let’s start by installing VS Code. Go to https://code.visualstudio.com/download to download VS Code from their official website.

Once, the download is complete, install VSCode by running the setup. Make sure to check all these options before installing.

Now, once you have installed VSCode, open VSCode and go to the Extensions Tab.

Here on the top search bar, search for “Live Server” and install this extension.

We are ready to create our project now.

Frontend of the Page We will start by designing the frontend of our website. Let’s add this HTML 5 Boilerplate and start the live server by right clicking anywhere on the editor and then choosing on the option “Open with Live Server”:

<!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>
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>

When you start the live server, your browser will automatically launch, and it will take you to http://127.0.0.1:5500/. If it doesn’t, you can manually type this to the browser URL and go there. This is what you will see if you have used the above boilerplate.

Let’s add a navbar by using the <nav> class and a footer using the <footer> class as shown below:

<nav>
    <div class="logo">MyCurrencyConverter</div>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About Us</a></li>
        <li><a href="/contact">Contact</a></li>
    </ul>
</nav>

<h1>Hello World!</h1>

<footer>
    Copyright &copy; All rights reserved
</footer>

Note to Readers:

You may notice links in the navigation bar like "/about" and "/contact." At present, these pages are placeholders and you can add these pages to your website if you wish to.

Now, we will start adding a form where we will take the desired information as form input and we will also add a button to submit the information.

 <div class="container">
        <h1>Choose a currency to convert</h1>
        <form action="/action.php" method="get">
            <label for="quantity">Choose a quantity: </label>
            <input type="number" name="quantity" min="1" max="10">
            <label for="currency">Choose a currency: </label>
            <select name="currency">
                <option value="INR">Indian Rupee</option>
                <option value="USD">US Dollar</option>
                <option value="EUR">Euro</option>
            </select>
            <button class="btn" type="submit">Submit</button>
        </form>
    </div>

Now, all that’s left is the output. We will add the output part and set its class as “output”. The output will have CSS "display:none" which will hide it until the data is fetched from the API

<div class="output">
    <h2>Here is your converted values in different currencies</h2>
    <table>
        <thead>
            <tr>
                <th>Currency</th>
                <th>Code</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
</div>

This is how it will look like:

I know, it does not look good at all. Let’s fix it by adding CSS styles to it.

Adding Styles

We have 3 methods to add CSS to our application.

  1. Internal CSS
  2. External CSS
  3. Inline CSS

We will focus on adding internal css for now. You can later organize your CSS in an external stylesheet.

Let’s go inside the <head> element and add our styles there. I have added the following styles:

<style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,700;1,300&family=Poppins:wght@400;600&display=swap');

        * {
            margin: 0;
            padding: 0;
        }

        nav {
            font-family: 'Noto Sans', sans-serif;
            font-weight: 900;
            display: flex;
            font-size: 20px;
            background-color: rgb(224, 209, 245);
            padding: 23px;
        }

        nav li a {
            text-decoration: none;
            color: rgb(2, 3, 18);
            transition: all;
            transition-duration: 500ms;
        }

        nav li a:hover {
            text-decoration: none;
            color: rgb(103, 101, 235);
        }

        div.logo {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 23px;
            font-size: 24px;
        }

        nav ul li {
            list-style: none;
            margin: 0 23px;
        }

        nav ul {
            display: flex;
        }

        .container {
            min-height: 100vh;
            font-family: 'Poppins', sans-serif;
            max-width: 80vw;
            margin: auto;
        }

        .container h1,
        h2 {
            margin: 23px 0;
        }

        .container form {
            display: flex;
            flex-direction: column;
        }

        .container form label {
            font-size: 25px;
        }

        .container form input[type='number'],
        select,
        label {
            font-size: 25px;
            width: 23vw;
            margin-bottom: 23px;
        }

        .btn {
            width: 144px;
            padding: 5px 8px;
            font-size: 20px;
            background: #e0d0f5;
            color: black;
            border-radius: 13px;
            cursor: pointer;
        }

        .output {
            display: none;
        }

        .output table {
            width: 50vw;
            text-align: center;
            border: 2px solid black;
            font-size: 20px;
        }

        .output table th{
            padding: 3px;
        }

        @media (max-width: 600px) {
            

            nav {
                flex-direction: column;
                font-size: 14px;
            }

            nav ul li {
                margin: 5px 13px;
            }

            nav ul {
                justify-content: center;
            }

            .container {
                max-width: 95vw;
            }

            .container form input[type='number'],
            select,
            label {
                width: 80vw;
            }
        }

        footer {
            font-family: 'Poppins', sans-serif;
            text-align: center;
        }
    </style>

After adding all the relevant styles, this is how our webpage will look:

We are done with the frontend part. Now, we will start coding the logic where we will use an API to fetch and convert the currency

Writing the JavaScript Logic

We will use CurrencyAPI.com for this application. CurrencyAPI.com provides us with currency conversion API which is the perfect tool to handle our exchange rate conversions. Create an account and you can use the free plan as it gives us 1 API Key and 300 Free Requests. If you need it for a large-scale application, you can purchase a subscription to this API. Let’s start by creating a new file called main.js and integrating it into our main page. We will add this line just below the footer.

<script src="main.js"></script>

Now, in the main.js file we will add the following code:

const populate = async (value, currency) => {
    let myStr = ""
    url = "https://api.currencyapi.com/v3/latest?apikey=API+KEY+HERE&base_currency=" + currency
    let response = await fetch(url)
    let rJson = await response.json()
    document.querySelector(".output").style.display = "block"

    for (let key of Object.keys(rJson["data"])) {
        myStr += ` <tr>
                        <td>${key}</td>
                        <td>${rJson["data"][key]["code"]}</td>
                        <td>${Math.round(rJson["data"][key]["value"] * value)}</td>
                    </tr> 
                `
    }
    const tableBody = document.querySelector("tbody");
    tableBody.innerHTML = myStr;

}
const btn = document.querySelector(".btn")
btn.addEventListener("click", (e) => {
    e.preventDefault()
    const value = parseInt(document.querySelector("input[name='quantity']").value);
    const currency = document.querySelector("select[name='currency']").value
    populate(value, currency)
})

In this code, we've created a function named populate to establish a functional currency conversion web application. We've harnessed an external API to fetch the latest currency exchange rates. By considering what the user enters for the amount and the desired currency type, we perform calculations to determine the converted value. The populate() function takes two arguments: the value of the quantity input and the currency selected from the dropdown menu. The function first creates an empty string called myStr. Then, it loops through the data object in the JSON response, which contains the currency rates. For each currency, the function adds a new row to the myStr string with the currency name, code, and the value of the currency multiplied by the quantity. Once the loop is finished, the myStr string is set as the innerHTML of the tbody element. This will update the table with the new currency rates. The btn element is an HTML button that has an event listener attached to it. When the button is clicked, the populate() function is called with the value of the quantity input and the currency selected from the dropdown menu. This will update the table with the new currency rates. Make sure to change this line to your own API key. You can get your own API Key by logging in to your currencyapi.com account

 url = "https://api.currencyapi.com/v3/latest?apikey=API+KEY+HERE&base_currency=" + currency

Now our application is finished. This is how the final product will look:

Conclusion & Github Link

With our application now fully operational, users can effortlessly convert currency by inputting the desired quantity and selecting the target currency. The table updates instantaneously, displaying the converted values for various currencies. This user-friendly interface streamlines the process of currency conversion and enhances financial decision-making. Here is the Github link for the project source code. Hope you learned something new. Happy Coding!

Add a new comment

Login to comment...

Comments (0)