Coding classic

html, css, javascript, react, python

Learn to Code a Currency Converter: A Step-by-Step Tutorial Using HTML, CSS, and JavaScript

Welcome to today’s tutorial, where we’ll be building a practical and useful Currency Converter using HTML, CSS, and JavaScript. This project is perfect for coders of all levels, from beginners to enthusiasts, looking to add a valuable feature to their websites. We’ll use HTML to create the foundation, CSS to add some visual flair, and JavaScript to bring the conversion functionality to life. Join me on this coding adventure as we create a simple yet effective Currency Converter. Let’s dive in and get started on this fun and easy-to-follow project!

HTML :

This HTML file establishes the user interface for a currency converter, featuring input fields for specifying the amount to be converted, dropdown menus for selecting the original and target currencies, and a button to initiate the conversion process. The exchange rate is displayed in real-time. The accompanying JavaScript file, linked at the bottom of the HTML document, is expected to contain the logic for performing the currency conversions and making API requests to retrieve the necessary exchange rate data.

Here’s a breakdown of the HTML code with comments:

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Specify the character encoding for the document -->
  <meta charset="UTF-8">
  <!-- Title of the web page displayed in the browser tab -->
  <title>Currency Converter by codingclassic</title>
  <!-- Link to an external stylesheet for Font Awesome icons -->
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css'>
  <!-- Link to an external Google Font (Montserrat) -->
  <link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&display=swap'>
  <!-- Link to the custom CSS file for additional styling -->
  <link rel="stylesheet" href="./style.css">
</head>

<body>
<!-- Main container for the currency converter application -->
<div class="wrapper">
  <!-- Header of the currency converter displaying the title -->
  <header>Currency Converter</header>
  
  <!-- Form where users will input data for conversion -->
  <form action="#">
    <!-- Container for entering the amount to convert -->
    <div class="amount">
      <p>Enter Amount</p>
      <!-- Input field with a default value of "1" -->
      <input type="text" value="1">
    </div>
    
    <!-- Container for selecting the currency options -->
    <div class="drop-list">
      <!-- Sub-container for the "From" currency selection -->
      <div class="from">
        <p>From</p>
        <!-- Container for the flag and the currency dropdown -->
        <div class="select-box">
          <!-- Image of the flag representing the selected "From" currency -->
          <img src="https://flagcdn.com/48x36/us.png" alt="flag">
          <!-- Dropdown to select the "From" currency (options will be populated via JavaScript) -->
          <select>
            <!-- Options tags are inserted from JavaScript -->
          </select>
        </div>
      </div>

      <!-- Icon representing the exchange action (switch between currencies) -->
      <div class="icon"><i class="fas fa-exchange-alt"></i></div>

      <!-- Sub-container for the "To" currency selection -->
      <div class="to">
        <p>To</p>
        <!-- Container for the flag and the currency dropdown -->
        <div class="select-box">
          <!-- Image of the flag representing the selected "To" currency -->
          <img src="https://flagcdn.com/48x36/in.png" alt="flag">
          <!-- Dropdown to select the "To" currency (options will be populated via JavaScript) -->
          <select>
            <!-- Options tags are inserted from JavaScript -->
          </select>
        </div>
      </div>
    </div>

    <!-- Display area for the exchange rate or status message -->
    <div class="exchange-rate">Getting exchange rate...</div>
    
    <!-- Button to trigger the exchange rate calculation -->
    <button>Get Exchange Rate</button>
  </form>
</div>

<!-- Link to the external JavaScript file that handles the currency conversion logic -->
<script src="./script.js"></script>

</body>
</html>

CSS :

This CSS code is responsible for visually styling a currency converter interface. It defines the layout and aesthetic for various elements, including input fields, dropdown menus, exchange rate displays, and buttons. The design features a sleek dark theme with bold color contrasts, and incorporates interactive effects such as hover and active states for the button. Additionally, the code employs the modern Montserrat font and a gradient background to create a visually appealing and cohesive design.

/* Reset default margin and padding for all elements, 
   set the box-sizing to border-box, and use the Montserrat font for the entire document */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Montserrat", sans-serif;
}

/* Style the body to center its content horizontally and vertically,
   set the background to a gradient, and ensure it covers at least the entire viewport height */
body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: linear-gradient(180deg, #fff 50%, #a16574 50%);
}

/* Customize the appearance of selected text (highlighted text) */
::selection {
  color: #000;
  background: #fff;
}

/* Style the main container (wrapper) for the form */
.wrapper {
  width: 370px; /* Fixed width for the form container */
  padding: 30px; /* Padding inside the container */
  border-radius: 5px; /* Rounded corners */
  background: #222; /* Dark background color */
  box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.2); /* Box shadow for a subtle 3D effect */
  color: #fff; /* White text color */
}

/* Style the header within the wrapper */
.wrapper header {
  font-size: 28px; /* Large font size */
  font-weight: 500; /* Medium font weight */
  text-align: center; /* Center the text */
}

/* Style the form element within the wrapper */
.wrapper form {
  margin: 40px 0 20px 0; /* Margin to separate the form from other content */
}

/* Apply styles to input, select, and button elements within the form */
form :where(input, select, button) {
  width: 100%; /* Full width */
  outline: none; /* Remove outline on focus */
  border-radius: 5px; /* Rounded corners */
  border: none; /* Remove default borders */
  background: #444; /* Dark background color */
  color: #fff; /* White text color */
}

/* Style the paragraph elements within the form */
form p {
  font-size: 18px; /* Font size for the label text */
  margin-bottom: 5px; /* Space below the label text */
}

/* Style the input fields within the form */
form input {
  height: 50px; /* Fixed height */
  font-size: 17px; /* Font size for input text */
  padding: 0 15px; /* Padding inside the input */
  border: 1px solid #999; /* Border color */
  background: #555; /* Slightly lighter background color */
}

/* Add a focus effect to input fields */
form input:focus {
  padding: 0 14px; /* Adjust padding on focus */
  border: 2px solid #675afe; /* Blue border on focus */
  background: #555; /* Keep the background color consistent */
}

/* Style the container for the currency dropdown lists */
form .drop-list {
  display: flex; /* Flexbox for alignment */
  margin-top: 20px; /* Space above the dropdown list */
  align-items: center; /* Center the items vertically */
  justify-content: space-between; /* Distribute space between items */
}

/* Style the select-box containers */
.drop-list .select-box {
  display: flex; /* Flexbox for alignment */
  width: 115px; /* Fixed width */
  height: 45px; /* Fixed height */
  align-items: center; /* Center the items vertically */
  border-radius: 5px; /* Rounded corners */
  justify-content: center; /* Center the items horizontally */
  border: 1px solid #999; /* Border color */
  background: #fff; /* White background color */
  color: #000; /* Black text color */
}

/* Style the images within the select boxes */
.select-box img {
  max-width: 21px; /* Limit the width of the flag images */
}

/* Style the select elements (dropdowns) within the select boxes */
.select-box select {
  width: auto; /* Auto width to fit content */
  font-size: 16px; /* Font size for dropdown text */
  background: none; /* No background */
  margin: 0 -5px 0 5px; /* Adjust the margin */
  color: #000; /* Black text color */
}

/* Customize the scrollbar appearance for the select elements */
.select-box select::-webkit-scrollbar {
  width: 8px; /* Width of the scrollbar */
}

.select-box select::-webkit-scrollbar-track {
  background: #fff; /* Background color of the scrollbar track */
}

.select-box select::-webkit-scrollbar-thumb {
  background: #888; /* Thumb color */
  border-radius: 8px; /* Rounded scrollbar thumb */
  border-right: 2px solid #ffffff; /* Right border of the scrollbar thumb */
}

/* Style the icon (swap button) in the drop list */
.drop-list .icon {
  cursor: pointer; /* Pointer cursor on hover */
  margin-top: 30px; /* Space above the icon */
  font-size: 22px; /* Font size for the icon */
  color: #fff; /* White color for the icon */
}

/* Style the exchange rate text within the form */
form .exchange-rate {
  font-size: 17px; /* Font size for the exchange rate text */
  margin: 20px 0 30px; /* Space around the exchange rate text */
}

/* Style the submit button within the form */
form button {
  height: 52px; /* Fixed height */
  color: #fff; /* White text color */
  font-size: 17px; /* Font size for the button text */
  cursor: pointer; /* Pointer cursor on hover */
  background: #444; /* Dark background color */
  transition: background 0.3s ease, transform 0.2s ease; /* Smooth transition for background and transform */
}

/* Change the button background color on hover */
form button:hover {
  background: #333; /* Darker background color on hover */
}

/* Apply a scale effect when the button is clicked */
form button:active {
  transform: scale(0.95); /* Slightly shrink the button */
}

JavaScript:

This JavaScript code powers a currency exchange rate calculator, enabling users to convert between different currencies. It begins by defining a list of currency codes and their corresponding country codes, which are then used to dynamically populate two dropdown menus. Users can select the source and target currencies, enter an amount, and then retrieve the current exchange rate. The code utilizes an API to fetch the exchange rate data, using a provided API key for authentication, and then displays the result to the user in real-time.

// Define a mapping of currency codes to their corresponding country codes.
let country_list = {
  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"
};

// Define the API key for the currency exchange rate API.
let apiKey = "e759f92560e41c99ee6213a2";

// Select all <select> elements in the form, and assign specific ones to variables.
const dropList = document.querySelectorAll("form select"),
  fromCurrency = document.querySelector(".from select"),
  toCurrency = document.querySelector(".to select"),
  getButton = document.querySelector("form button");

// Loop through the dropdown lists and populate them with currency options.
for (let i = 0; i < dropList.length; i++) {
  for (let currency_code in country_list) {
    // Set the default selected options: "USD" for the first dropdown, "INR" for the second.
    let selected =
      i == 0
        ? currency_code == "USD"
          ? "selected"
          : ""
        : currency_code == "INR"
        ? "selected"
        : "";
    // Create an option tag for each currency and append it to the dropdown list.
    let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
    dropList[i].insertAdjacentHTML("beforeend", optionTag);
  }
  // Add an event listener to load the corresponding country flag when the selected currency changes.
  dropList[i].addEventListener("change", (e) => {
    loadFlag(e.target);
  });
}

// Function to load and display the flag of the selected currency.
function loadFlag(element) {
  for (let code in country_list) {
    if (code == element.value) {
      let imgTag = element.parentElement.querySelector("img");
      // Set the image source to the corresponding country's flag.
      imgTag.src = `https://flagcdn.com/48x36/${country_list[
        code
      ].toLowerCase()}.png`;
    }
  }
}

// When the window loads, automatically fetch and display the exchange rate.
window.addEventListener("load", () => {
  getExchangeRate();
});

// Add an event listener to the button to fetch the exchange rate when clicked.
getButton.addEventListener("click", (e) => {
  e.preventDefault(); // Prevent the form from submitting.
  getExchangeRate(); // Fetch the exchange rate.
});

// Add an event listener to the exchange icon to swap the selected currencies.
const exchangeIcon = document.querySelector("form .icon");
exchangeIcon.addEventListener("click", () => {
  let tempCode = fromCurrency.value;
  fromCurrency.value = toCurrency.value;
  toCurrency.value = tempCode;
  loadFlag(fromCurrency);
  loadFlag(toCurrency);
  getExchangeRate(); // Fetch the exchange rate for the new currency pair.
});

// Function to fetch and display the exchange rate.
function getExchangeRate() {
  const amount = document.querySelector("form input"); // Get the input element for the amount.
  const exchangeRateTxt = document.querySelector("form .exchange-rate"); // Get the element to display the exchange rate.
  let amountVal = amount.value; // Get the amount value from the input field.
  if (amountVal == "" || amountVal == "0") {
    amount.value = "1"; // Default to 1 if the input is empty or zero.
    amountVal = 1;
  }
  exchangeRateTxt.innerText = "Getting exchange rate..."; // Display a loading message.
  // Build the API URL using the selected "from" currency.
  let url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency.value}`;
  // Fetch the exchange rate data from the API.
  fetch(url)
    .then((response) => response.json()) // Parse the response as JSON.
    .then((result) => {
      let exchangeRate = result.conversion_rates[toCurrency.value]; // Get the exchange rate for the "to" currency.
      let totalExRate = (amountVal * exchangeRate).toFixed(2); // Calculate the converted amount.
      exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`; // Display the exchange rate.
    })
    .catch(() => {
      exchangeRateTxt.innerText = "Something went wrong"; // Handle any errors during the fetch.
    });
}

Conclusion

Well done, coders! We’ve successfully completed our Currency Converter project using HTML, CSS, and JavaScript. This functional tool is now ready to be integrated into your projects, providing a practical solution for users. Regardless of whether you carefully followed each step or quickly skimmed through the tutorial, I hope you’ve gained valuable coding insights and experience that will benefit your future projects.

Learn to Code a Currency Converter: A Step-by-Step Tutorial Using HTML, CSS, and JavaScript

Leave a Reply

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

Scroll to top