HomeJavascriptCurrency Converter With Javascript

Currency Converter With Javascript

Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn Javascript. So in today’s tutorial let us expand our javascript knowledge with a fun and easy-to-build project called ‘Currency Converter’. To build this project we need HTML, CSS, and Javascript.

Video Tutorial:

For a better understanding of how we built the functionality of this project, I would advise you to watch the video below. If you find the video helpful give it a like and subscribe to my YouTube channel where I post new tips, tricks, and tutorials related to HTML, CSS, and Javascript.

Project Folder Structure:

Let’s build the project folder structure before we begin writing the code. We create a project folder called ‘Currency Converter’. Inside this folder, we have index.html, style.css, script.js, currency-codes.js, API-key.js, and SVG icon files.

HTML:

We begin with the HTML Code. First, create a file called – ‘index.html’. Copy the code below and paste it into your HTML file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Currency Converter</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet-->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div class="app-details">
        <img src="app-icon.svg" class="app-icon" />
        <h1 class="app-title">Currency Converter</h1>
      </div>
      <label for="amount">Amount:</label>
      <input type="number" id="amount" value="100" />
      <div class="dropdowns">
        <select id="from-currency-select"></select>
        <select id="to-currency-select"></select>
      </div>
      <button id="convert-button">Convert</button>
      <p id="result"></p>
    </div>

    <!-- Scipt With Array Of Supported Country Codes -->
    <script src="currency-codes.js"></script>
    <!-- Script with API Key -->
    <script src="api-key.js"></script>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our list using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  border: none;
  outline: none;
}
body {
  background-color: #9873fe;
}
.wrapper {
  width: 90%;
  max-width: 25em;
  background-color: #ffffff;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  padding: 2em;
  border-radius: 0.8em;
}
.app-details {
  display: flex;
  align-items: center;
  flex-direction: column;
}
.app-icon {
  width: 9.37em;
}
.app-title {
  font-size: 1.6em;
  text-transform: uppercase;
  margin-bottom: 1em;
}
label {
  display: block;
  font-weight: 600;
}
input#amount {
  font-weight: 400;
  font-size: 1.2em;
  display: block;
  width: 100%;
  border-bottom: 2px solid #02002c;
  color: #7a789d;
  margin-bottom: 2em;
  padding: 0.5em;
}
input#amount:focus {
  color: #9873fe;
  border-color: #9873fe;
}
.dropdowns {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1em;
}
select {
  width: 100%;
  padding: 0.6em;
  font-size: 1em;
  border-radius: 0.2em;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url("arrow-down.svg");
  background-repeat: no-repeat;
  background-position: right 15px top 50%, center;
  background-size: 20px 20px;
  background-color: #9873fe;
  color: #ffffff;
}
select option {
  background-color: #ffffff;
  color: #02002c;
}
button {
  font-size: 1em;
  width: 100%;
  background-color: #9873fe;
  padding: 1em 0;
  margin-top: 2em;
  border-radius: 0.3em;
  color: #ffffff;
  font-weight: 600;
}
#result {
  font-size: 1.2em;
  text-align: center;
  margin-top: 1em;
  color: #02002c;
  background-color: #e5dbff;
  padding: 0.8em 0;
}

Javascript:

Finally, we add functionality using Javascript. Once again copy the code below and paste it into your script file.

Before moving to actual implementation we store the API key in the file ‘api-key.js’ and store all the currency codes in the ‘currency-codes.js’ file.

Then let’s move on to the implementation steps:

  • Create initial HTML references and store the API URL in a variable
  • Fill Currency codes in dropdown options
  • When the user clicks on the convert button or when the page loads we call the ‘convertCurrency’ function
  • The ‘convertCurrency’ function stores the values of both the dropdowns that the user has chosen or based on default values
  • Now if the user hasn’t submitted a blank amount we make a GET request to the API URL using the ‘fetch’ method.
  • The API returns current rates for each currency
  • Now we convert the entered amount to another currency using the fetched rate and display it upto two decimals
let api = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
const fromDropDown = document.getElementById("from-currency-select");
const toDropDown = document.getElementById("to-currency-select");

//Create dropdown from the currencies array
currencies.forEach((currency) => {
  const option = document.createElement("option");
  option.value = currency;
  option.text = currency;
  fromDropDown.add(option);
});

//Repeat same thing for the other dropdown
currencies.forEach((currency) => {
  const option = document.createElement("option");
  option.value = currency;
  option.text = currency;
  toDropDown.add(option);
});

//Setting default values
fromDropDown.value = "USD";
toDropDown.value = "INR";

let convertCurrency = () => {
  //Create References
  const amount = document.querySelector("#amount").value;
  const fromCurrency = fromDropDown.value;
  const toCurrency = toDropDown.value;

  //If amount input field is not empty
  if (amount.length != 0) {
    fetch(api)
      .then((resp) => resp.json())
      .then((data) => {
        let fromExchangeRate = data.conversion_rates[fromCurrency];
        let toExchangeRate = data.conversion_rates[toCurrency];
        const convertedAmount = (amount / fromExchangeRate) * toExchangeRate;
        result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(
          2
        )} ${toCurrency}`;
      });
  } else {
    alert("Please fill in the amount");
  }
};

document
  .querySelector("#convert-button")
  .addEventListener("click", convertCurrency);
window.addEventListener("load", convertCurrency);
//Paste your generated api Key here
let apiKey = "";

Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the ‘Download Code’ button below.

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

1 × four =

Most Popular