Develop a Currency Converter in JavaScript

 

Develop a Currency Converter in JavaScript


Developing a currency converter in JavaScript involves creating a simple web interface to input values, select currencies, and display the converted amount. You will typically use a currency exchange rate API to get the latest exchange rates. Here, I'll provide an example that uses the Exchange Rate-API, but you can use any API you prefer.

Step-by-Step Guide

Step 1: HTML Structure

Create a simple HTML file with input fields for the amount and currency selection, and a place to display the converted amount.


<!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> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .converter { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .converter input, .converter select, .converter button { display: block; width: 100%; margin: 10px 0; padding: 10px; font-size: 16px; } .result { margin-top: 20px; font-size: 18px; } </style> </head> <body> <div class="converter"> <h1>Currency Converter</h1> <input type="number" id="amount" placeholder="Enter amount" required> <select id="fromCurrency"></select> <select id="toCurrency"></select> <button onclick="convertCurrency()">Convert</button> <div class="result" id="result"></div> </div> <script src="script.js"></script> </body> </html>


Step 2: JavaScript for Fetching Exchange Rates and Conversion

Create a JavaScript file (script.js) to fetch the exchange rates and handle the conversion logic.


// script.js // Replace 'YOUR_API_KEY' with your actual API key from ExchangeRate-API const apiKey = 'YOUR_API_KEY'; const apiURL = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`; const fromCurrency = document.getElementById('fromCurrency'); const toCurrency = document.getElementById('toCurrency'); const amount = document.getElementById('amount'); const result = document.getElementById('result'); // Fetch currency options and exchange rates fetch(apiURL) .then(response => response.json()) .then(data => { const currencies = Object.keys(data.conversion_rates); populateCurrencyOptions(currencies); }) .catch(error => console.error('Error fetching exchange rates:', error)); function populateCurrencyOptions(currencies) { currencies.forEach(currency => { const option1 = document.createElement('option'); const option2 = document.createElement('option'); option1.value = option2.value = currency; option1.textContent = option2.textContent = currency; fromCurrency.appendChild(option1); toCurrency.appendChild(option2); }); } function convertCurrency() { const from = fromCurrency.value; const to = toCurrency.value; const amountValue = amount.value; if (amountValue === '' || isNaN(amountValue)) { result.textContent = 'Please enter a valid amount'; return; } fetch(`https://v6.exchangerate-api.com/v6/${apiKey}/pair/${from}/${to}/${amountValue}`) .then(response => response.json()) .then(data => { result.textContent = `${amountValue} ${from} = ${data.conversion_result.toFixed(2)} ${to}`; }) .catch(error => console.error('Error converting currency:', error)); }


Explanation

  1. HTML Structure:

    • Input fields for amount and currency selection (fromCurrency and toCurrency).
    • A button to trigger the conversion.
    • A div to display the result.
  2. JavaScript:

    • Fetch Exchange Rates: On page load, fetch the latest exchange rates from the ExchangeRate-API.
    • Populate Currency Options: Dynamically populate the currency selection dropdowns with the available currencies.
    • Convert Currency: Fetch the conversion rate for the selected currencies and amount, and display the result.

Important Notes

  • API Key: You need to sign up for an API key from Exchange Rate-API or any other currency conversion API service you choose.
  • Error Handling: Basic error handling is included to alert users in case of network issues or invalid input.

This simple currency converter provides a good foundation. You can enhance it with additional features like historical data, currency symbols, and more advanced error handling based on your needs.

Create a JavaScript file (script.js) to fetch the exchange rates and handle the conversion logic.

j



You'll learn today in this post how to create a JavaScript currency converter.

With the help of this Currency Converter, which we created using JavaScript, you may change any currency into another.

You might like this






HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=1">
<title>Home</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
    <h1>Currency Converter</h1>
    <div class="row">
      <div class="col">
        <select name="currency" class="currency"> 
        <option>select</option>
        </select>
        <input type="text" name="" id="input_currency">
      </div>
      <div class="col">
        <select name="currency" class="currency">
        <option>select</option>
        </select>
        <input type="text" name="" id="output_currency" disabled>
      </div>
    </div>
    <button onClick="convert()">Convert</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>




CSS Code

*,*:after,*:before{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
body{
font-family: arial;
font-size: 16px;
margin: 0;
background: linear-gradient(to right bottom, #007673, #0e0066);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.container{
width: 600px;
}
h1{
font-size: 60px;
text-align: center;
}
.row{
display: flex;
align-items: center;
justify-content: space-between;
}
.col{
width: 48%;
}
select,
input{
width: 100%;
margin-bottom: 15px;
font-size: 20px;
padding:8px 15px;
font-weight: 700
}
input{
width: 100%;
padding: 10px 15px;
}
button{
width: 200px;
display: block;
padding: 10px;
text-align: center;
margin:0 auto;
font-size: 22px;
border-radius: 15px;
background-color: #e62e00;
color: #fff;
border:0;
cursor: pointer;
}




JavaScript Code

var select = document.querySelectorAll(".currency"),
input_currency = document.getElementById('input_currency'),
output_currency = document.getElementById('output_currency');
fetch(`https://api.frankfurter.app/currencies`)
  .then((data) => data.json())
  .then((data) => {
    const entries = Object.entries(data);
    console.log(data)
  for (var i = 0; i < entries.length; i++) {
    select[0].innerHTML += `<option value="${entries[i][0]}">${entries[i][0]}</option>`;
    select[1].innerHTML += `<option value="${entries[i][0]}">${entries[i][0]}</option>`;
  }   
});
function convert(){
  input_currency_val = input_currency.value;
  if(select[0].value != select[1].value ){
  alert("yes")
  const host = 'api.frankfurter.app';
fetch(`https://${host}/latest?amount=${input_currency_val}&from=${select[0].value}&to=${select[1].value}`)
  .then((val) => val.json())
    .then((val) => {
    //alert(`10 GBP = ${data.rates.USD} USD`);
    output_currency.value = Object.values(val.rates)[0]
    console.log(Object.values(val.rates)[0])
});
  }else{
  alert("Peease select two different currencies")
  }
}

Post a Comment

0 Comments