Learn to Develop a Currency Converter App with HTML, CSS, and JavaScript

Learn to Develop a Currency Converter App with HTML, CSS, and JavaScript

Introduction:

In today's digital age, currency conversion has become an essential tool for travelers, businesses, and anyone dealing with multiple currencies. With the rise of online shopping and global trade, the need for quick and accurate currency conversion is more important than ever. Developing a currency converter app is a great way to enhance your web development skills while creating a practical tool that can be used in real-world scenarios. In this tutorial, we will guide you through the process of building a simple yet effective currency converter app using HTML, CSS, and JavaScript. Whether you're a beginner or looking to refresh your skills, this project will provide you with a solid foundation in web development and a deeper understanding of how to work with APIs and dynamic data. Let's get started!

HTML CODE :

<!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="currency.css"/>
    <!--for font taking-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.1/css/all.min.css" integrity="sha512-5Hs3dF2AEPkpNAR7UiOHba+lRSJNeM2ECkwxUIxC1Q/FLycGTbNapWXB4tP889k5T5Ju8fs4b1P5z/iB4nMfSQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

</head>
<body>
    <header>
        <h2>Currency Converter</h2>
    </header>
    <main>
        <div class="container">





            <!---Amount SEction-->

            <div class="amount">
            <label for="Amount">Enter Amount :</label>
            <input type="text" name="Amount" placeholder="Enter Amount" required>
        </div>

        <!--From Section-->

        <div class="dropdown">
        <div class="from">
        <h5>From</h5>
        <img src="https://flagsapi.com/US/flat/64.png">
        <div class="select">
            <select name="from"> </select>
        </div></div>



        <i class="fa-solid fa-arrow-right-arrow-left"></i>


        <!--to section-->


            <div class="to">
            <h5>To</h5>
            <img src="https://flagsapi.com/IN/flat/64.png">
            <div class="select">
                <select name="to"></select>
            </div></div>
            </div>

            <div class="btn">
                <button type="submit">Exchange</button>
            </div>

            <div class="exchangerate">
                <p>1 USD = 80 INR </p>
            </div>




        </div>
    </main>

    <script src="country.js"></script>
    <script src="currency.js"></script>
</body>
</html>

The HTML code is for a currency exchange interface. It includes several sections:

  • Amount Section: This part has a label and a text input field where users can enter the amount they want to exchange.

  • From Section: This section allows users to select the currency they are exchanging from. It includes a dropdown menu and displays a flag image for the United States.

  • To Section: Similar to the "From" section, this part lets users choose the currency they want to exchange to, with a dropdown menu and a flag image for India.

  • Exchange Button: A button labeled "Exchange" that users can click to perform the currency exchange.

  • Exchange Rate Display: A paragraph showing the current exchange rate, for example, "1 USD = 80 INR."

The code also includes links to two JavaScript files, country.js and currency.js, which likely handle the functionality for selecting countries and calculating currency conversions.

CSS CODE:

/* currency.css */

body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    color: #333;
    margin: 0;
    padding: 0;
}

header {
    background-color: #4CAF50;
    color: white;
    padding: 10px 0;
    text-align: center;
   text-shadow: lightcyan 0 0 100px;
}

h2 {
    margin: 0;
}

.container {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    background-color: white;
    border-radius: 10px;
    box-shadow: rgb(0, 0, 0, 0.1) 0px 0px 5.419px, 
    rgb(0, 0, 0, 0.1) 0px 0px 5.954px,
    rgb(0, 0, 0, 0.1) 0px 0px 5.473px,
    rgb(0, 0, 0, 0.1) 0px 0px 5.736px,
    rgb(0, 0, 0, 0.1) 0px 0px 5.4961px,
    rgb(0, 0, 0, 0.1) 0px 0px 5.2481px;
}

.amount, .dropdown {
    margin: 20px 0;
}

label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
}

input[type="text"] {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
}

.from, .to {
    display: flex;
    align-items: center;
    gap: 5px;
}

.from img, .to img {
    margin-right: 10px;
}

.select {
    flex-grow: 1;
}

select {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
}

.fa-arrow-right-arrow-left {
    display: block;
    text-align: center;
    margin: 20px auto;
    margin-left: 300px;
    font-size: 24px;
    color: #4CAF50;
    transform: rotate(90deg); /* Rotate the arrow by 90 degrees */
}


.btn {
    text-align: center;
    margin-top: 20px;
}

.btn button {
    background-color: #4CAF50; 
    border: darkgreen;
    color: white; 
    padding: 15px 32px; 
    text-align: center; 
    text-decoration: none; 
    display: inline-block;
    font-size: 16px; 
    margin: 4px 2px; 
    cursor: pointer; 
    border-radius: 8px; 
    transition: background-color 0.3s ease; 
}


.btn button:hover {
    background-color: darkgreen;
}

.exchangerate {
    text-align: center;
    margin-top: 20px;
    font-size: 18px; 
    color: #333;
    display: flex;
}


.exchangerate p {
    margin: 0;
    padding: 10px;
    background-color: #f0f0f0; 
    border-radius: 8px; 
    display: inline-block;
}

The code above is a CSS stylesheet that styles various elements on a webpage. Here's a breakdown:

  • The .from and .to classes align items in a row with a small gap and add a margin to the right of images.

  • The .select class allows the element to expand and fill available space.

  • The select element is styled to be wide, with padding, a border, and rounded corners.

  • The .fa-arrow-right-arrow-left class centers an arrow icon, rotates it 90 degrees, and colors it green.

  • The .btn class centers a button and adds a top margin.

  • The button inside .btn has a green background, white text, padding, and rounded corners. It changes color when hovered over.

  • The .exchangerate class centers text, adds a top margin, and displays it in a larger font.

  • The paragraph inside .exchangerate has no margin, padding, a light gray background, and rounded corners.

JS CODE:

const API_KEY = "your Api"; // Replace with your actual API key
const BASE_URL = `https://v6.exchangerate-api.com/v6/${API_KEY}/latest`;

// Select elements
const dropdowns = document.querySelectorAll(".dropdown select");
const exchangeBtn = document.querySelector(".btn button");
const fromCurrency = document.querySelector(".from select");
const toCurrency = document.querySelector(".to select");
const amountInput = document.querySelector(".amount input");
const exchangeRateText = document.querySelector(".exchangerate p");
const swapBtn = document.querySelector(".fa-arrow-right-arrow-left");

// Populate currency dropdowns
for (let select of dropdowns) {
    for (let currencyCode in countryList) {
        let option = document.createElement("option");
        option.innerText = currencyCode;
        option.value = currencyCode;

        // Default selection
        if (select.name === "from" && currencyCode === "USD") {
            option.selected = true;
        } else if (select.name === "to" && currencyCode === "INR") {
            option.selected = true;
        }

        select.appendChild(option);
    }

    // Update flag when currency selection changes
    select.addEventListener("change", function () {
        updateFlag(this);
    });
}

// Function to fetch and update exchange rate
const updateExchangeRate = async () => {
    let amount = amountInput.value;

    // Ensure the amount is valid
    if (!amount || Number(amount) < 1) {
        amount = 1;
        amountInput.value = "1";
    }

    const fromCurr = fromCurrency.value;
    const toCurr = toCurrency.value;
    const url = `${BASE_URL}/${fromCurr}`; // Fetch rates for 'from' currency

    try {
        let response = await fetch(url);
        if (!response.ok) throw new Error(`API Error: ${response.status}`);

        let data = await response.json();

        if (!data.conversion_rates[toCurr]) throw new Error("Exchange rate not found!");

        let rate = data.conversion_rates[toCurr];
        let convertedAmount = (amount * rate).toFixed(2);
        exchangeRateText.innerText = `${amount} ${fromCurrency.value} = ${convertedAmount} ${toCurrency.value}`;
    } catch (error) {
        console.error("Error fetching exchange rate:", error);
        exchangeRateText.innerText = "Error fetching exchange rate. Try again!";
    }
};

// Function to update country flag based on currency selection
const updateFlag = (element) => {
    let currencyCode = element.value;
    let countryCode = countryList[currencyCode];

    if (countryCode) {
        let flagUrl = `https://flagsapi.com/${countryCode}/flat/64.png`;

        if (element.name === "from") {
            document.querySelector(".from img").src = flagUrl;
        } else if (element.name === "to") {
            document.querySelector(".to img").src = flagUrl;
        }
    }
};

// Event listener for Exchange button
exchangeBtn.addEventListener("click", (event) => {
    event.preventDefault();
    updateExchangeRate();
});

// Swap button functionality
swapBtn.addEventListener("click", () => {
    let tempCurrency = fromCurrency.value;
    fromCurrency.value = toCurrency.value;
    toCurrency.value = tempCurrency;

    updateFlag(fromCurrency);
    updateFlag(toCurrency);
    updateExchangeRate();
});

// Initialize exchange rate and flags on page load
window.addEventListener("load", () => {
    updateExchangeRate();
    updateFlag(fromCurrency);
    updateFlag(toCurrency);
});

This code manages currency exchange rates and updates country flags based on the selected currencies. Here's a breakdown of its functionality:

  • Error Handling: If there's an issue fetching the exchange rate, an error message is displayed: "Error fetching exchange rate. Try again!"

  • Flag Update Function: The updateFlag function changes the country flag image based on the selected currency. It retrieves the country code from a list using the currency code and updates the flag's image URL.

  • Exchange Button: An event listener is set up for the "Exchange" button. When clicked, it prevents the default form submission and calls the updateExchangeRate function to refresh the exchange rate.

  • Swap Button: The "Swap" button switches the selected currencies. It swaps the values of the "from" and "to" currency fields, updates the flags, and refreshes the exchange rate.

  • Page Load Initialization: When the page loads, it initializes by updating the exchange rate and setting the correct flags for the selected currencies.

JS CODE FOR COUNTRY LIST:

const countryList = {
    AED: "AE",
    AFN: "AF",
    XCD: "AG",
    ALL: "AL",
    AMD: "AM",
    ANG: "AN",
    AOA: "AO",
    AQD: "AQ",
    ARS: "AR",
    AUD: "AU",
    AZN: "AZ",
    BAM: "BA",
    BBD: "BB",
    BDT: "BD",
    XOF: "BE",
    BGN: "BG",
    BHD: "BH",
    BIF: "BI",
    BMD: "BM",
    BND: "BN",
    BOB: "BO",
    BRL: "BR",
    BSD: "BS",
    NOK: "BV",
    BWP: "BW",
    BYR: "BY",
    BZD: "BZ",
    CAD: "CA",
    CDF: "CD",
    XAF: "CF",
    CHF: "CH",
    CLP: "CL",
    CNY: "CN",
    COP: "CO",
    CRC: "CR",
    CUP: "CU",
    CVE: "CV",
    CYP: "CY",
    CZK: "CZ",
    DJF: "DJ",
    DKK: "DK",
    DOP: "DO",
    DZD: "DZ",
    ECS: "EC",
    EEK: "EE",
    EGP: "EG",
    ETB: "ET",
    EUR: "FR",
    FJD: "FJ",
    FKP: "FK",
    GBP: "GB",
    GEL: "GE",
    GGP: "GG",
    GHS: "GH",
    GIP: "GI",
    GMD: "GM",
    GNF: "GN",
    GTQ: "GT",
    GYD: "GY",
    HKD: "HK",
    HNL: "HN",
    HRK: "HR",
    HTG: "HT",
    HUF: "HU",
    IDR: "ID",
    ILS: "IL",
    INR: "IN",
    IQD: "IQ",
    IRR: "IR",
    ISK: "IS",
    JMD: "JM",
    JOD: "JO",
    JPY: "JP",
    KES: "KE",
    KGS: "KG",
    KHR: "KH",
    KMF: "KM",
    KPW: "KP",
    KRW: "KR",
    KWD: "KW",
    KYD: "KY",
    KZT: "KZ",
    LAK: "LA",
    LBP: "LB",
    LKR: "LK",
    LRD: "LR",
    LSL: "LS",
    LTL: "LT",
    LVL: "LV",
    LYD: "LY",
    MAD: "MA",
    MDL: "MD",
    MGA: "MG",
    MKD: "MK",
    MMK: "MM",
    MNT: "MN",
    MOP: "MO",
    MRO: "MR",
    MTL: "MT",
    MUR: "MU",
    MVR: "MV",
    MWK: "MW",
    MXN: "MX",
    MYR: "MY",
    MZN: "MZ",
    NAD: "NA",
    XPF: "NC",
    NGN: "NG",
    NIO: "NI",
    NPR: "NP",
    NZD: "NZ",
    OMR: "OM",
    PAB: "PA",
    PEN: "PE",
    PGK: "PG",
    PHP: "PH",
    PKR: "PK",
    PLN: "PL",
    PYG: "PY",
    QAR: "QA",
    RON: "RO",
    RSD: "RS",
    RUB: "RU",
    RWF: "RW",
    SAR: "SA",
    SBD: "SB",
    SCR: "SC",
    SDG: "SD",
    SEK: "SE",
    SGD: "SG",
    SKK: "SK",
    SLL: "SL",
    SOS: "SO",
    SRD: "SR",
    STD: "ST",
    SVC: "SV",
    SYP: "SY",
    SZL: "SZ",
    THB: "TH",
    TJS: "TJ",
    TMT: "TM",
    TND: "TN",
    TOP: "TO",
    TRY: "TR",
    TTD: "TT",
    TWD: "TW",
    TZS: "TZ",
    UAH: "UA",
    UGX: "UG",
    USD: "US",
    UYU: "UY",
    UZS: "UZ",
    VEF: "VE",
    VND: "VN",
    VUV: "VU",
    YER: "YE",
    ZAR: "ZA",
    ZMK: "ZM",
    ZWD: "ZW",
  };

This tutorial guides you through building a simple currency converter app using HTML, CSS, and JavaScript, ideal for enhancing web development skills. The app allows users to enter an amount, select currencies to convert from and to, and displays the exchange rate and converted amount. It includes functionalities for currency selection, flag updates, and rate fetching via API. The project helps in understanding dynamic data handling and API integration, while providing practical use for travelers and businesses dealing with multiple currencies.