Thursday, January 30, 2025

How to Create a Currency Converter Like XE.com

You can create a currency converter similar to XE.com using HTML, CSS, and JavaScript, and by retrieving real-time exchange rate data from an API. Below is a complete guide and a code example for building a basic currency converter.

1. Use a Currency Exchange Rate API
You can use a free ExchangeRate-API or any other currency exchange API to fetch real-time exchange rate data. First, you’ll need to sign up at https://www.exchangerate-api.com and get an API key.

2. Create the Frontend Interface
Here is a simple HTML, CSS, and JavaScript example to create a basic currency converter UI that mimics XE.com, utilizing ExchangeRate-API for fetching the exchange rate.

HTML + CSS + JavaScript 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>
        body {
            font-family: Arial, sans-serif;
            background-color: #f3f4f6;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 400px;
        }

        h1 {
            text-align: center;
            font-size: 24px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }

        input, select, button {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        .result {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <div class="container">
        <h1>Currency Converter</h1>
        
        <div class="form-group">
            <label for="amount">Amount</label>
            <input type="number" id="amount" placeholder="Enter amount">
        </div>

        <div class="form-group">
            <label for="fromCurrency">From Currency</label>
            <select id="fromCurrency">
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
                <option value="GBP">GBP</option>
                <option value="INR">INR</option>
                <option value="CNY">CNY</option>
            </select>
        </div>

        <div class="form-group">
            <label for="toCurrency">To Currency</label>
            <select id="toCurrency">
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
                <option value="GBP">GBP</option>
                <option value="INR">INR</option>
                <option value="CNY">CNY</option>
            </select>
        </div>

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

        <div class="result" id="result"></div>
    </div>

    <script>
        const apiKey = 'YOUR_API_KEY';  // Replace with your ExchangeRate-API key
        const apiUrl = 'https://v6.exchangerate-api.com/v6/' + apiKey + '/latest/';

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

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

            const url = `${apiUrl}${fromCurrency}`;
            try {
                const response = await fetch(url);
                const data = await response.json();

                if (data.result === 'error') {
                    alert('Error fetching data');
                    return;
                }

                const exchangeRate = data.conversion_rates[toCurrency];
                const convertedAmount = (amount * exchangeRate).toFixed(2);

                document.getElementById('result').textContent = 
                    `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to fetch exchange rates');
            }
        }
    </script>

</body>
</html>

Explanation:
HTML Part:

amount: Input field where the user can enter the amount they wish to convert.
fromCurrency and toCurrency: Dropdowns to select the source and destination currencies.
convertCurrency(): JavaScript function that fetches the exchange rate from the API and displays the result.
CSS Part:

Basic styling to make the interface clean and user-friendly.
JavaScript Part:

Uses the fetch API to retrieve exchange rate data from ExchangeRate-API.
Calculates the converted amount based on the fetched exchange rate and displays it on the page.
3. Get the API Key
You’ll need to sign up at ExchangeRate-API to get your free API key. Once you have your key, replace YOUR_API_KEY in the JavaScript code.

4. Run the Project
Save the code as index.html.
Open it in a browser directly or serve it via a local server (for example, using python -m http.server).
5. Enhance and Expand
More Currencies: Add more options to the currency dropdowns in fromCurrency and toCurrency.
Error Handling: You can enhance error handling, especially if the API request fails or the entered amount is invalid.
UI Improvements: Improve the user interface with more styling (e.g., adding loading spinners, better input validation, etc.).
This basic setup will allow you to create a simple currency converter similar to XE.com. The user can enter the amount, choose the currencies, and click “Convert” to see the converted amount.