Mastering HTML: Creating a Simple Interactive Website with a Basic Currency Converter

In today’s globalized world, dealing with different currencies is a common occurrence. Whether you’re traveling, shopping online, or managing international finances, a currency converter can be an incredibly useful tool. Building one yourself, even a simple version, is a fantastic way to learn HTML, JavaScript, and get a taste of how web applications work. This tutorial will guide you through creating a basic, yet functional, currency converter using HTML. We’ll cover everything from the basic structure to adding interactivity, making it a perfect project for beginners and intermediate developers alike.

Why Build a Currency Converter?

Creating a currency converter offers several advantages:

  • Practical Application: You’ll learn a skill that has real-world applications.
  • Foundation in Web Development: You’ll gain a solid understanding of fundamental web technologies.
  • Interactive Experience: You’ll build a project that users can actively engage with.
  • Portfolio Piece: It’s a great project to showcase your skills.

Setting Up the HTML Structure

Let’s start by creating the basic HTML structure for our currency converter. This involves setting up the necessary elements for user input, displaying the results, and providing a clear and organized layout. Create a file named currency_converter.html and add the following code:

<!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>
        /* Add basic styling here */
        body {
            font-family: sans-serif;
            margin: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="number"], select {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            cursor: pointer;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h2>Currency Converter</h2>
    <div>
        <label for="amount">Amount:</label>
        <input type="number" id="amount" placeholder="Enter amount">

        <label for="fromCurrency">From:</label>
        <select id="fromCurrency">
            <option value="USD">USD (US Dollar)</option>
            <option value="EUR">EUR (Euro)</option>
            <option value="GBP">GBP (British Pound)</option>
            <!-- Add more currencies here -->
        </select>

        <label for="toCurrency">To:</label>
        <select id="toCurrency">
            <option value="EUR">EUR (Euro)</option>
            <option value="USD">USD (US Dollar)</option>
            <option value="GBP">GBP (British Pound)</option>
            <!-- Add more currencies here -->
        </select>

        <button onclick="convertCurrency()">Convert</button>

        <div id="result"></div>
    </div>
    <script>
        // JavaScript will go here
    </script>
</body>
</html>

This code sets up the basic HTML elements:

  • A title for the page.
  • Input fields for the amount to be converted.
  • Dropdown menus (<select>) for selecting the currencies.
  • A button to trigger the conversion.
  • A <div> element to display the result.

We’ve also included basic CSS styling within the <style> tags to make the elements look presentable.

Adding JavaScript for Interactivity

Now, let’s add the JavaScript code that will handle the currency conversion logic. This involves fetching exchange rates, performing the calculation, and displaying the result. Place this JavaScript code within the <script> tags in your HTML file:


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

    // Check if the amount is a valid number
    if (isNaN(amount) || amount <= 0) {
        resultDiv.textContent = 'Please enter a valid amount.';
        return;
    }

    // Replace with your actual API key and endpoint
    const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
    const apiUrl = `https://api.exchangerate-api.com/v4/latest/${fromCurrency}`;

    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const rates = data.rates;
            const toRate = rates[toCurrency];

            if (!toRate) {
                resultDiv.textContent = 'Conversion rate not available.';
                return;
            }

            const convertedAmount = amount * toRate;
            resultDiv.textContent = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(2)} ${toCurrency}`;
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
            resultDiv.textContent = 'An error occurred during conversion.';
        });
}

Let’s break down this JavaScript code:

  • convertCurrency() Function: This function is triggered when the