Build a simple currency exchange rate application usingHTML and JavaScript.

Hey, I am Ajink, and today in this blog, we’re going to build a straightforward yet effective currency exchange rate application using HTML and JavaScript. This application will empower users to quickly convert between different currencies, providing them with real-time exchange rates.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Currency Exchange Rate App</title>
</head>
<body>
  <div class="exchange-container">
    <h1>Currency Exchange Rate</h1>
    <div class="input-container">
      <label for="amount">Amount:</label>
      <input type="number" id="amount" placeholder="Enter amount">
    </div>
    <div class="select-container">
      <label for="fromCurrency">From:</label>
      <select id="fromCurrency"></select>
    </div>
    <div class="select-container">
      <label for="toCurrency">To:</label>
      <select id="toCurrency"></select>
    </div>
    <button onclick="convertCurrency()">Convert</button>
    <p id="result">Result: </p>
  </div>
  <script src="app.js"></script>
</body>
</html>

HTML Code Explanation:

  • The HTML structure consists of a container for the application, input fields for amount and currency selection, and a button to perform the conversion. The result is displayed below the button.

CSS Code:

body {
  margin: 0;
  font-family: 'Arial', sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.exchange-container {
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.input-container,
.select-container {
  margin-bottom: 10px;
}

label {
  margin-right: 10px;
}

input,
select {
  padding: 8px;
}

button {
  background-color: #3498db;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#result {
  font-weight: bold;
}

CSS Code Explanation:

  • The CSS provides styling for the currency exchange application, including colors, shadows, and spacing.

JavaScript Code:

document.addEventListener('DOMContentLoaded', function () {
  const fromCurrencySelect = document.getElementById('fromCurrency');
  const toCurrencySelect = document.getElementById('toCurrency');

  // Replace with your own API key from Open Exchange Rates
  const apiKey = 'YOUR_OPENEXCHANGERATES_API_KEY';
  const apiUrl = `https://open.er-api.com/v6/latest`;

  fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
      const currencies = Object.keys(data.rates);

      currencies.forEach(currency => {
        const option = document.createElement('option');
        option.value = currency;
        option.text = currency;
        fromCurrencySelect.add(option.cloneNode(true));
        toCurrencySelect.add(option);
      });
    })
    .catch(error => console.error('Error fetching currency data:', error));
});

function convertCurrency() {
  const amount = document.getElementById('amount').value;
  const fromCurrency = document.getElementById('fromCurrency').value;
  const toCurrency = document.getElementById('toCurrency').value;

  if (!amount || isNaN(amount) || amount <= 0) {
    alert('Please enter a valid amount.');
    return;
  }

  fetch(`${apiUrl}?base=${fromCurrency}`)
    .then(response => response.json())
    .then(data => {
      const rate = data.rates[toCurrency];
      const result = amount * rate;

      document.getElementById('result').innerText = `Result: ${amount} ${fromCurrency} = ${result.toFixed(2)} ${toCurrency}`;
    })
    .catch(error => console.error('Error converting currency:', error));
}

JavaScript Code Explanation:

  • The JavaScript code dynamically populates the currency dropdowns using the Open Exchange Rates API.
  • The convertCurrency function is triggered when the “Convert” button is clicked, fetching the exchange rate and displaying the result.

Conclusion:

In this blog, we successfully built a simple currency exchange rate application using HTML and JavaScript. Users can now enter an amount, select the source and target currencies, and click the “Convert” button to get the converted result. Don’t forget to subscribe to my YouTube channel at youtube.com/@ajink21 for more exciting tutorials.

Thanks for reading, and if you have any doubts, feel free to comment!

Ajink Gupta
Ajink Gupta
Articles: 54