In our globalized world, currency conversion is essential for travelers, businesses, and even casual shoppers. Imagine needing to know how much your dollar is worth in euros before making a purchase. A Currency Converter in Minutes Using a JavaScript currency converter is your best friend in such scenarios. But instead of relying on third-party tools, why not build your own using JavaScript? It’s easier than you think!

Understanding the Basics

What is a Currency Converter in Minutes Using JavaScript?

A currency converter is a tool that allows you to convert one currency into another based on current exchange rates. It’s essential for travelers, businesses, and anyone dealing with multiple currencies.

Importance of Currency Converters

In today’s global economy, currency converters are invaluable. They help individuals and businesses make informed financial decisions, travel with ease, and conduct international transactions seamlessly.

What is JavaScript?

JavaScript is a powerful, versatile programming language widely used to create interactive effects within web browsers. It’s an essential tool for front-end developers and plays a critical role in modern web development.

Key Features of JavaScript

JavaScript offers various features such as dynamic typing, prototype-based object orientation, and first-class functions. It allows you to create dynamic web pages that respond to user inputs, making it perfect for our currency converter.

How JavaScript Interacts with HTML and CSS

JavaScript works seamlessly with HTML and CSS to enhance the functionality and appearance of web pages. HTML provides the structure, CSS styles the content, and JavaScript adds interactivity.

Creating the HTML Structure

Basic HTML Layout

Start with a basic HTML structure:

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>ACZone - Currency Converter using JS</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Currency Converter using JS</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css'>
<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&amp;display=swap'><link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<div class="wrapper">
  <header>Currency Converter</header>
  <form action="#">
    <div class="amount">
      <p>Enter Amount</p>
      <input type="text" value="1">
    </div>
    <div class="drop-list">
      <div class="from">
        <p>From</p>
        <div class="select-box">
          <img src="https://flagcdn.com/48x36/us.png" alt="flag">
          <select>
            <!-- Options tag are inserted from JavaScript -->
          </select>
        </div>
      </div>
      <div class="icon"><i class="fas fa-exchange-alt"></i></div>
      <div class="to">
        <p>To</p>
        <div class="select-box">
          <img src="https://flagcdn.com/48x36/in.png" alt="flag">
          <select>
            <!-- Options tag are inserted from JavaScript -->
          </select>
        </div>
      </div>
    </div>
    <div class="exchange-rate">Getting exchange rate...</div>
    <button>Get Exchange Rate</button>
  </form>
</div>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>

Adding Input Fields

The input fields allow users to enter the amount they want to convert and select the currencies.

Creating Dropdown Menus for Currencies

Populate the dropdowns with currency options. This can be done dynamically using JavaScript, which we’ll cover later.

Adding a Convert Button

A simple button triggers the conversion process.

Styling with CSS

Basic CSS for Layout

Create a styles.css file to style your converter. Here’s a basic layout:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Montserrat", sans-serif;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #47289d;
}

::selection {
  color: #000;
  background: #fff;
}

.wrapper {
  width: 370px;
  padding: 30px;
  border-radius: 5px;
  background: #222;
  box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.2);
  color: #fff;
}

.wrapper header {
  font-size: 28px;
  font-weight: 500;
  text-align: center;
}

.wrapper form {
  margin: 40px 0 20px 0;
}

form :where(input, select, button) {
  width: 100%;
  outline: none;
  border-radius: 5px;
  border: none;
  background: #444;
  color: #fff;
}

form p {
  font-size: 18px;
  margin-bottom: 5px;
}

form input {
  height: 50px;
  font-size: 17px;
  padding: 0 15px;
  border: 1px solid #999;
  background: #555;
}

form input:focus {
  padding: 0 14px;
  border: 2px solid #675afe;
  background: #555;
}

form .drop-list {
  display: flex;
  margin-top: 20px;
  align-items: center;
  justify-content: space-between;
}

.drop-list .select-box {
  display: flex;
  width: 115px;
  height: 45px;
  align-items: center;
  border-radius: 5px;
  justify-content: center;
  border: 1px solid #999;
  background: #fff;
  color: #000;
}

.select-box img {
  max-width: 21px;
}

.select-box select {
  width: auto;
  font-size: 16px;
  background: none;
  margin: 0 -5px 0 5px;
  color: #000;
}

.select-box select::-webkit-scrollbar {
  width: 8px;
}

.select-box select::-webkit-scrollbar-track {
  background: #fff;
}

.select-box select::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}

.drop-list .icon {
  cursor: pointer;
  margin-top: 30px;
  font-size: 22px;
  color: #fff;
}

form .exchange-rate {
  font-size: 17px;
  margin: 20px 0 30px;
}

form button {
  height: 52px;
  color: #fff;
  font-size: 17px;
  cursor: pointer;
  background: #444;
  transition: background 0.3s ease, transform 0.2s ease;
}

form button:hover {
  background: #333;
}

form button:active {
  transform: scale(0.95);
}

Enhancing User Interface with CSS

Add more styles to make your converter visually appealing. Consider using CSS animations and transitions for a smoother user experience.

Writing the JavaScript Code

Introduction to Fetch API

The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). It’s a modern and straightforward way to interact with APIs.

Fetching Currency Exchange Rates

Use an exchange rate API to get current rates. For example, you can use the ExchangeRate-API. Here’s how to fetch data:

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"
};

let apiKey = "e759f92560e41c99ee6213a2";

const dropList = document.querySelectorAll("form select"),
  fromCurrency = document.querySelector(".from select"),
  toCurrency = document.querySelector(".to select"),
  getButton = document.querySelector("form button");

for (let i = 0; i < dropList.length; i++) {
  for (let currency_code in country_list) {
    let selected =
      i == 0
        ? currency_code == "USD"
          ? "selected"
          : ""
        : currency_code == "INR"
        ? "selected"
        : "";
    let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
    dropList[i].insertAdjacentHTML("beforeend", optionTag);
  }
  dropList[i].addEventListener("change", (e) => {
    loadFlag(e.target);
  });
}

function loadFlag(element) {
  for (let code in country_list) {
    if (code == element.value) {
      let imgTag = element.parentElement.querySelector("img");
      imgTag.src = `https://flagcdn.com/48x36/${country_list[
        code
      ].toLowerCase()}.png`;
    }
  }
}

window.addEventListener("load", () => {
  getExchangeRate();
});

getButton.addEventListener("click", (e) => {
  e.preventDefault();
  getExchangeRate();
});

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();
});

function getExchangeRate() {
  const amount = document.querySelector("form input");
  const exchangeRateTxt = document.querySelector("form .exchange-rate");
  let amountVal = amount.value;
  if (amountVal == "" || amountVal == "0") {
    amount.value = "1";
    amountVal = 1;
  }
  exchangeRateTxt.innerText = "Getting exchange rate...";
  let url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency.value}`;
  fetch(url)
    .then((response) => response.json())
    .then((result) => {
      let exchangeRate = result.conversion_rates[toCurrency.value];
      let totalExRate = (amountVal * exchangeRate).toFixed(2);
      exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`;
    })
    .catch(() => {
      exchangeRateTxt.innerText = "Something went wrong";
    });
}

FAQs

What Are the Key Advantages of Using JavaScript for Currency Conversion?

JavaScript allows for real-time interaction and updates, making it ideal for applications that require live data, such as currency converters.

How Often Should I Update the Exchange Rates?

It depends on your use case. For most applications, updating rates once a day is sufficient. For financial applications, you might need to update more frequently.

Can I Add More Features to My Currency Converter?

Absolutely! You can add features like conversion history, graphical representations of exchange rates, and support for more currencies.

What Are Common Issues and How Do I Fix Them?

Common issues include incorrect exchange rates and API errors. Ensure your API key is correct and handle errors gracefully in your code.

Is It Necessary to Use an API for Exchange Rates?

While it’s possible to hardcode exchange rates, using an API ensures your rates are accurate and up-to-date.

Telegram Group Join Now
WhatsApp Group Join Now
Instagram Group Join Now

By aczone

Leave a Reply

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