Currency Converter Javascript

Mastering the skill of swiftly executing currency conversions will greatly benefit developers working on globally-targeted websites or applications. While alternative options exist, JavaScript stands out as an excellent choice for building a currency converter because of its versatility and widespread adoption. This guide will walk you through the process of creating a currency converter with JavaScript, offering a straightforward and effective approach.

Prerequisites: Proficiency in fundamental concepts of HTML, CSS, and JavaScript is essential. Additionally, it is necessary to have a code editor like Sublime Text or Visual Studio installed.

Setting Up the HTML Structure:

Create the basic structure of your currency converter in HTML beforehand. Begin by using the provided template below:

Example

<!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>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="converter">
        <h1>Currency Converter</h1>
        <label for="amount">Enter Amount:</label>
        <input type="number" id="amount" placeholder="Enter amount">

        <label for="fromCurrency">From Currency:</label>
        <select id="fromCurrency">
            
        </select>

        <label for="toCurrency">To Currency:</label>
        <select id="toCurrency">
            
        </select>

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

        <p id="result">Result will appear here</p>
    </div>

    <script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"></script>
</body>
</html>

Explanation:

At the beginning of the document, you will find the HTML markup that outlines the layout of the currency converter webpage. Subsequently, there is the standard declaration of the document type, along with meta elements specifying the viewport settings and character encoding. The webpage is titled "Currency Converter" and includes a link to the "styles.css" file for applying visual styles.

The content of the page is contained within a div element with the class "converter" situated in the body section. Within this container, the layout is structured in the following manner:

  • An h1 heading displaying "Currency Converter".
  • Input fields for users to enter the amount.
  • Dropdown menus for selecting both the source and target currencies.
  • A button named "Convert" which triggers a JavaScript function.
  • A paragraph element identified by the ID "result" to present the conversion output.

Creating the CSS Style (styles.css):

To enhance the visual appeal of your currency converter, consider adding a touch of design to make it unique and personalized to your preferences.

Example

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

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

input, select, button {
    margin-bottom: 10px; 
    padding: 8px; 
}

button {
    background-color: #4caf50;
    color: #fff;
    cursor: pointer;
    border: none; 
}

button:hover {
    background-color: #45a049;
}

Explanation:

The CSS script defines styles for developing a comprehensive and visually attractive currency converter website. A subtle grey shade is utilized for the background, while the content is vertically and horizontally aligned in the viewport through the application of flexbox properties. The font family for the page layout is established with Arial in the body segment. By setting the height to 100vh, the body will span the entire height of the viewport, ensuring a full-screen display.

The class named "converter" is characterized by a background color set to white, rounded corners (border-radius: 12px), and a slight box shadow effect that creates a sense of depth. Moving forward, let's delve into the design of the currency conversion container. In order to achieve a clean appearance, the content within the container is aligned centrally, and padding is utilized to provide spacing.

Below are the specifications for styling the input fields, buttons, and dropdown menus in the converter application. The gaps separating these components are consistent, with a set Margin-bottom of 10 pixels and a padding of 8 pixels designated for each element.

In conclusion, the "Convert" button now features a unique design. It includes text with a white background, an active cursor, and a green background color (#4caf50). This design appears more streamlined as the default button border has been removed. A hover effect has also been added to provide users with visual feedback, changing the button's background color to #45a049 when hovered over. The main goal of the CSS code is to enhance the aesthetics and user experience of the currency converter software interface.

Next, we will proceed to the JavaScript section (script.js):

Example

const exchangeRates = {
    USD: 1,
    EUR: 0.85,
    GBP: 0.73,
    JPY: 110.17,
    INR: 74.43,
};
const fromCurrencySelect = document.getElementById('fromCurrency');
const toCurrencySelect = document.getElementById('toCurrency');

For (let currency in exchangeRates) {
    
    const option1 = document.createElement('option');
    option1.value = currency; 
    option1.text = currency; 
    fromCurrencySelect.add(option1); 

    
    const option2 = document.createElement('option');
    option2.value = currency; 
    option2.text = currency; 
    toCurrencySelect.add(option2); 
}

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

    if (isNaN(amount)) {
        alert('Please enter a valid number');
        return;
    }

    // Calculate the converted amount using the exchange rates
    const convertedAmount = amount * (exchangeRates[toCurrency] / exchangeRates[fromCurrency]);

    // Update the HTML element with the ID 'result' to display the conversion result
    document.getElementById('result').innerText = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(2)} ${toCurrency}`;
}

Output:

The provided JavaScript snippet establishes a functional currency conversion feature that can be accessed on a website. Begin by defining an object named exchangeRates to hold the conversion rates between various currencies and the US dollar (USD). You can include rates for the British pound (GBP), Indian rupee (INR), Japanese yen (JPY), and euro (EUR) initially, and incorporate additional currencies as required.

Subsequently, the script utilizes a for-in iteration to dynamically create currency choices for the pair of dropdown lists within the HTML document, specifically designated by their IDs as "fromCurrency" and "toCurrency." For every currency listed in the exchangeRates object, the script generates two option elements, each assigned with the currency code for both text and value properties. These newly generated options are then used to update the content of the respective dropdown menus.

The script also provides a functionality named convertCurrency, which is triggered upon the user clicking the button in the HTML document. This functionality retrieves the amount, source currency, and target currency selected by the user. It validates whether the entered amount is a valid numerical value. If the input is invalid, a warning message prompts the user to enter a valid number. Upon correct input, the HTML element with the ID "result" displays the converted amount rounded to two decimal places. The conversion result is calculated based on the provided exchange rates formula.

In the JavaScript code provided, a conversion function is implemented to produce different outputs based on user input. This function dynamically populates currency choices to enhance the usability of a currency conversion tool.

Demonstrating the creation of a currency converter with JavaScript showcases the integration of data, logic, and user interfaces. Enhancing this project can be achieved by integrating real-time conversion rates through an API, adding new currency options, or improving the user interface. This simple illustration underscores the capabilities of JavaScript in web development and serves as a foundation for developing more complex financial applications.

Input Required

This code uses input(). Please provide values below: