Currency Converter with HTML, CSS, and JavaScript Using ExchangeRate API

Faraz

By Faraz -

Learn how to build a currency converter using HTML, CSS, and JavaScript, integrating ExchangeRate API for real-time currency conversion.


Creating a Currency Converter with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Currency conversion tools are essential for websites with international users. In this blog post, we will guide you through the process of creating a currency converter using HTML, CSS, and JavaScript, with the added benefit of real-time currency exchange rates via the ExchangeRate API.

Supported Currencies

The currency converter supports the following currencies:

  • AED (United Arab Emirates Dirham)
  • ARS (Argentine Peso)
  • AUD (Australian Dollar)
  • BGN (Bulgarian Lev)
  • BRL (Brazilian Real)
  • BSD (Bahamian Dollar)
  • CAD (Canadian Dollar)
  • CHF (Swiss Franc)
  • CLP (Chilean Peso)
  • CNY (Chinese Yuan)
  • COP (Colombian Peso)
  • CZK (Czech Koruna)
  • DKK (Danish Krone)
  • DOP (Dominican Peso)
  • EGP (Egyptian Pound)
  • EUR (Euro)
  • FJD (Fijian Dollar)
  • GBP (British Pound Sterling)
  • GTQ (Guatemalan Quetzal)
  • HKD (Hong Kong Dollar)
  • HRK (Croatian Kuna)
  • HUF (Hungarian Forint)
  • IDR (Indonesian Rupiah)
  • ILS (Israeli New Shekel)
  • INR (Indian Rupee)
  • ISK (Icelandic Króna)
  • JPY (Japanese Yen)
  • KRW (South Korean Won)
  • KZT (Kazakhstani Tenge)
  • MXN (Mexican Peso)
  • MYR (Malaysian Ringgit)
  • NOK (Norwegian Krone)
  • NZD (New Zealand Dollar)
  • PAB (Panamanian Balboa)
  • PEN (Peruvian Sol)
  • PHP (Philippine Peso)
  • PKR (Pakistani Rupee)
  • PLN (Polish Złoty)
  • PYG (Paraguayan Guarani)
  • RON (Romanian Leu)
  • RUB (Russian Ruble)
  • SAR (Saudi Riyal)
  • SEK (Swedish Krona)
  • SGD (Singapore Dollar)
  • THB (Thai Baht)
  • TRY (Turkish Lira)
  • TWD (New Taiwan Dollar)
  • UAH (Ukrainian Hryvnia)
  • USD (United States Dollar)
  • UYU (Uruguayan Peso)
  • VND (Vietnamese Đồng)
  • ZAR (South African Rand)

Let's start making an amazing currency converter using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our currency converter.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code step by step:

1. <!DOCTYPE html>: This is the document type declaration and specifies that the document is an HTML5 document.

2. <html lang="en">: This is the opening <html> tag, and it specifies that the document's primary language is English (en).

3. <head>: This is the head section of the HTML document, where metadata and other information about the page is included.

  • <meta charset="UTF-8">: This meta tag defines the character encoding of the document as UTF-8, which is a character encoding for Unicode.
  • <meta http-equiv="X-UA-Compatible" content="IE=Edge">: This meta tag is often used to specify the rendering mode for Internet Explorer. It sets the document to be displayed in the "Edge" mode.
  • <meta name="viewport" content="width=device-width, initial-scale=1">: This meta tag is commonly used for responsive web design. It sets the viewport width to the device width and sets the initial zoom scale to 1.
  • <title>Currency Converter</title>: This sets the title of the web page, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: This link tag references an external stylesheet named "styles.css," which is used to define the page's styling.

4. <body>: This is the body section of the HTML document, where the visible content of the web page is defined.

5. <h1>Currency Converter</h1>: This is the main heading of the web page, displaying "Currency Converter."

6. <div class="container">: This <div> element has the class "container" and contains the main content of the page.

7. <div class="currency">: This is a container for the currency conversion inputs and selectors.

8. <select id="currency-one">: This is a dropdown select element with the ID "currency-one." It allows the user to select the source currency from a list of options.

9. Inside this <select>, there are multiple <option> elements. Each <option> represents a currency with a unique value and displays its abbreviation.

10. <input type="number" id="amount-one" placeholder="0" value="1">: This is an input field of type "number" with the ID "amount-one." It allows the user to input the amount of the source currency they want to convert. The placeholder text is "0," and it initially has a value of "1."

11. <div class="swap-rate-container">: This <div> contains the "Swap" button and the exchange rate display.

  • <button class="btn" id="swap">Swap</button>: This is a button with the class "btn" and the ID "swap." It allows the user to switch the source and target currencies.
  • <div class="rate" id="rate"></div>: This empty <div> with the class "rate" and the ID "rate" is where the converted exchange rate will be displayed.

12. <div class="currency">: This is another container for the target currency selector and input.

  • <select id="currency-two">: Similar to "currency-one," this dropdown allows the user to select the target currency.
  • <input type="number" id="amount-two" placeholder="0">: This input field with the ID "amount-two" allows the user to input the converted amount. It initially displays "0."

13. <script src="script.js"></script>: This script tag references an external JavaScript file named "script.js." This JavaScript file contains the functionality for the currency conversion and interaction with the page elements.

This is the basic structure of our currency converter using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the currency converter is in place, the next step is to add styling to the converter using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our converter. Let me explain each section of the code:

1. * selector:

  • The asterisk (*) selector selects all elements on the page.
  • box-sizing: border-box; ensures that the width and height of elements include padding and borders.
  • margin: 0; and padding: 0; reset margin and padding for all elements, effectively eliminating default spacing.

2. body selector:

  • Styles for the entire page.
  • background-color: #f2f2f2; sets the background color to a light gray.
  • font-family: Arial, sans-serif; specifies the font family for text, with fallback to sans-serif fonts.
  • text-align: center; centers the text within the body.

3. h1 selector:

  • Styles for the main heading.
  • font-size: 32px; sets the font size to 32 pixels.
  • margin: 20px 0; provides top and bottom margin, but no left or right margin.

4. .container class:

  • Styles for a container element.
  • display: flex; creates a flex container.
  • justify-content: center; horizontally centers its children.
  • align-items: center; vertically centers its children.
  • flex-wrap: wrap; allows content to wrap to the next line if it overflows.
  • margin: 20px; adds margin around the container.

5. .currency class:

  • Styles for currency input elements.
  • display: flex; makes the elements inside flex containers.
  • flex-direction: column; stacks child elements vertically.
  • margin: 10px; adds spacing around these elements.
  • background-color: #fff; sets the background color to white.
  • border: 1px solid #ccc; gives a border with a light gray color.
  • border-radius: 5px; rounds the corners of the elements.
  • padding: 10px; adds padding inside these elements.
  • width: 250px; sets the width of these elements.
  • box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); adds a subtle box shadow for depth.

6. select, input selector:

  • Styles for select and input elements within the .currency class.
  • margin: 10px 0; provides spacing above and below these elements.
  • padding: 10px; adds padding inside the elements.
  • border: 1px solid #ccc; gives them a light gray border.
  • border-radius: 5px; rounds their corners.
  • width: 100%; makes them fill the container width.

7. .swap-rate-container class:

  • Styles for a container with a swap button and rate display.
  • display: flex; creates a flex container.
  • flex-direction: column; stacks child elements vertically.
  • align-items: center; vertically centers child elements.
  • margin: 20px; adds margin around the container.

8. .btn class:

  • Styles for a button element.
  • background-color: #007bff; sets the background color to a blue shade.
  • color: #fff; sets the text color to white.
  • border: none; removes the button border.
  • border-radius: 5px; rounds the button corners.
  • padding: 10px 20px; specifies padding inside the button.
  • cursor: pointer; changes the cursor to a pointer on hover.
  • transition: background-color 0.3s; adds a smooth color transition on hover.

9. .btn:hover selector:

  • Styles for the button when hovered.
  • background-color: #0056b3; changes the background color on hover.

10. .rate class:

  • Styles for a rate display.
  • font-size: 24px; sets the font size to 24 pixels.
  • margin-top: 10px; adds top margin.

11. Media queries:

  • These media queries apply different styles for various screen sizes.
  • For screens with a width less than or equal to 768px, the container becomes a column layout, and currency elements take up the full width.
  • For screens with a width less than or equal to 480px, the heading's font size decreases to 24px.

This will give our currency converter an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

/* Reset some default styles */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* Apply a background color and text styles */
body {
  background-color: #f2f2f2;
  font-family: Arial, sans-serif;
  text-align: center;
}

/* Style the heading */
h1 {
  font-size: 32px;
  margin: 20px 0;
}

/* Style the container for currency inputs */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  margin: 20px;
}

/* Style currency select and input elements */
.currency {
  display: flex;
  flex-direction: column;
  margin: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  width: 250px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

select, input {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 100%;
}

/* Style the swap button and rate display */
.swap-rate-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px;
}

.btn {
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn:hover {
  background-color: #0056b3;
}

.rate {
  font-size: 24px;
  margin-top: 10px;
}

/* Media queries for responsiveness */
@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }

  .currency {
    width: 100%;
  }
}

@media (max-width: 480px) {
  h1 {
    font-size: 24px;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let me explain each part of the code step by step:

1. The code begins by defining several variables using const to store references to various HTML elements. These elements are identified by their IDs using the getElementById method. They include:

  • currencyEl_one and currencyEl_two: These are dropdown elements where users can select two different currencies for conversion.
  • amountEl_one and amountEl_two: These are input fields where users can enter the amount to be converted from one currency to another.
  • rateEl: This is a <p> element used to display the exchange rate information.
  • swap: This is a button element that allows users to swap the selected currencies.

2. A calculated function is defined. This function is responsible for fetching exchange rate data from an API and updating the conversion result based on user input.

  • It first retrieves the selected currencies from currencyEl_one and currencyEl_two.
  • It then makes an API request to 'https://api.exchangerate-api.com/v4/latest/' to get exchange rate data for the currency specified in currencyEl_one.
  • It processes the API response in two chained .then() functions. The first one parses the response as JSON, and the second one extracts the exchange rate for the second selected currency from the response.
  • The exchange rate information is displayed in the rateEl paragraph.
  • The conversion result is calculated and displayed in amountEl_two based on the amount entered by the user and the exchange rate.

3. Event listeners are set up to trigger the calculate function whenever there is a change in the selected currencies (currencyEl_one and currencyEl_two) or an input in the amount fields (amountEl_one and amountEl_two).

4. Another event listener is added to the swap button. When this button is clicked, the selected currencies in currencyEl_one and currencyEl_two are swapped, and the calculate function is called again to update the conversion result.

5. Finally, the calculate function is called once to initialize the conversion result when the page loads.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const currencyEl_one = document.getElementById('currency-one');
const currencyEl_two = document.getElementById('currency-two');
const amountEl_one = document.getElementById('amount-one');
const amountEl_two = document.getElementById('amount-two');
const rateEl = document.getElementById('rate');
const swap = document.getElementById('swap');


function calculate() {
  const currency_one = currencyEl_one.value;
  const currency_two = currencyEl_two.value;

  //fetching the api
  fetch(`https://api.exchangerate-api.com/v4/latest/${currency_one}`)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      console.log(data);

      const rate = data.rates[currency_two];
      rateEl.innerText = `1 ${currency_one} = ${rate} ${currency_two}`;
      amountEl_two.value = (amountEl_one.value * rate).toFixed(2);
    });
}

currencyEl_one.addEventListener('change', calculate);
amountEl_one.addEventListener('input', calculate);
currencyEl_two.addEventListener('change', calculate);
amountEl_two.addEventListener('input', calculate);

swap.addEventListener('click', function() {
  const temp = currencyEl_one.value;

  currencyEl_one.value = currencyEl_two.value;

  currencyEl_two.value = temp;
  calculate();
});

calculate();

Final Output:

Creating a Currency Converter with HTML, CSS, and JavaScript.gif

Conclusion:

In this blog post, you've learned how to create a dynamic currency converter using HTML, CSS, and JavaScript. By integrating the ExchangeRate API, you've made your converter even more valuable to users. Now, you can confidently add this feature to your website, enhancing the user experience.

Following these steps can provide a seamless and efficient currency conversion tool for your website visitors. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post