Building a Simple Currency Converter with HTML, JavaScript, and CSS
A currency converter is a useful tool that allows users to convert an amount from one currency to another based on exchange rates. In this blog post, we will walk through the process of building a simple currency converter using HTML, JavaScript, and CSS. This converter will use fixed exchange rates and allow users to input an amount, select currencies, and see the converted value instantly.
Features of Our Currency Converter:
✔ Converts an amount from one currency to another ✔ Uses fixed exchange rates for simplicity ✔ Supports USD, EUR, and GBP ✔ Provides instant conversion upon button click ✔ Styled for a clean and simple user experience
Step 1: Writing the HTML Structure
We start by creating a basic HTML structure that includes:
Here's our HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Currency Converter</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
max-width: 400px;
margin: auto;
background: #fefefe;
}
input, select, button {
padding: 8px;
margin: 5px;
font-size: 16px;
width: calc(100% - 20px);
}
#result {
margin-top: 20px;
font-size: 18px;
text-align: center;
color: #333;
}
</style>
</head>
<body>
<h1>Currency Converter</h1>
<input type="number" id="amount" placeholder="Amount" step="any">
<select id="fromCurrency">
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="GBP">GBP</option>
</select>
<select id="toCurrency">
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="GBP">GBP</option>
</select>
<button id="convertCurrency">Convert</button>
<div id="result"></div>
</body>
</html>
Explanation:
Step 2: Adding JavaScript Logic
Next, we write the JavaScript code to handle currency conversion. Since we're using fixed exchange rates, we'll define a conversion table with predefined values.
<script>
// Fixed conversion rates relative to USD
const conversionRates = {
USD: 1,
EUR: 0.85,
GBP: 0.75
};
document.getElementById("convertCurrency").addEventListener("click", function() {
const amount = parseFloat(document.getElementById("amount").value);
const fromCurrency = document.getElementById("fromCurrency").value;
const toCurrency = document.getElementById("toCurrency").value;
if (isNaN(amount)) {
document.getElementById("result").textContent = "Please enter a valid amount.";
return;
}
// Convert the amount to USD, then to the target currency
const amountInUSD = amount / conversionRates[fromCurrency];
const convertedAmount = amountInUSD * conversionRates[toCurrency];
document.getElementById("result").textContent =
amount + " " + fromCurrency + " = " + convertedAmount.toFixed(2) + " " + toCurrency;
});
</script>
How It Works:
Step 3: Enhancing the User Experience
To make the converter more user-friendly, we applied some CSS styles:
Example Usage:
Thank you. This is a good refresher for me. I haver a tendency to learn too many things at once and forget the things I need