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
HTML Structure:
- Input fields for amount and currency selection (
fromCurrency
andtoCurrency
). - A button to trigger the conversion.
- A
div
to display the result.
- Input fields for amount and currency selection (
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
0 Comments