Create a Currency Converter

Create a Currency Converter

Table of Contents

  1. Introduction
  2. Setting Up the HTML File
  3. Creating the CSS File
  4. Adding JavaScript Code
  5. Fetching Exchange Rates
  6. Populating Dropdown Options
  7. Converting Currency
  8. Displaying Converted Rates
  9. Swapping Values
  10. Conclusion

Introduction

In this tutorial, we will learn how to create a currency converter using JavaScript. We will start by setting up the HTML file and including the necessary CSS and JavaScript files. Then, we will fetch exchange rates from an API and populate the dropdown options. We will also create functions to convert currency values and display the converted rates. Finally, we will add a feature to swap the input values. Let's get started!

Setting Up the HTML File

To begin, open your code editor and create an HTML file. Use the <link> tag to include the CSS file and copy the code for the <link> tag to include the Material Icons into the project. In the <body>, create a <div> element with the class container. Inside it, create an <h2> element with the class heading. We will type "Currency Converter" inside it. Create a <div> element with the class rate inside the container. Inside it, create two <div> elements with the classes rate1 and rate2, respectively. Now create a <div> element with the class main, which will contain the main body of the converter. Create a <div> element with the class initial inside it. Inside the initial div, create a <div> element with the class options and an empty <select> tag inside it. Create a sibling <div> with the class input and put an <input> type number inside it. Now create a <span> element with the class material-icons. Add a second class swap to it and use an inline style to set the font size to 36 pixels. Put the name of the icon inside it, which is "swap_horiz". Repeat the initial div, but this time change its class to target and add the disabled attribute to its <input> element. Next, create a <button> with the class result. Lastly, use a <script> tag to include our JavaScript file.

Creating the CSS File

Now let's create the CSS file. Import the "Yantra Mono" font from Google Fonts. For the <body>, set the height to 100vh and display to flex. Justify content to center and align items to center. Set the background image to a linear gradient with its direction as to bottom. The first color is a shade of magenta-pink, while the second color is a shade of bluish magenta. Set overflow to hidden. For the .container class, set the background color to white, width to 470 pixels, height to 360 pixels, and padding to 70 pixels. Set the box shadow to 0 pixels xy offset, 50 pixels blur radius, and color to black with 50% opacity. Set the border radius to 5 pixels and font family to "Yantra Mono", monospace serif. For the .heading class, set the color to a medium-dark shade of bluish magenta. Set text alignment to center, text transform to uppercase, and font size to 2.8 rem. For the .rate class, set the margin top to -1.5 rem. For the .rate1 class, set the color to gray. For the .rate2 class, set the margin top to 0.5 rem and font size to 1.5 rem. For the .main class, set display to flex, flex direction to row, justify content to space between, and margin top to 2 rem. For the .swap class, set align self to flex end, padding to 5 pixels, and cursor to pointer. For the .options class, set the select element's padding to 2 percent and width to 75 pixels. For the .input class, set the input element's attributes as mentioned above. For the .target class, set the transform to translateX with a value of -5. For the .result class, set the margin top to 1.5 rem, width to 100%, height to 50 pixels, text alignment to center, color to white, and background color to the same color used for the heading. Set the outline and border to none and border radius to 5 pixels. For the .result.active selector, set the background color to a dark shade of the previous color. Our CSS is ready.

Adding JavaScript Code

Now let's move on to the JavaScript part. We will start by selecting some elements. Select the .rate1 and .rate2 elements. Select the result button. Select all the select elements with the options class using querySelectorAll. Assign the first select element to the cell1 variable and the second one to the cell2 variable. Do the same with the inputs. Declare an empty rates object where we will store all the exchange rates. Let's store the API URL in a variable. It is https://api.exchangerate.host/latest with its base parameter set to USD. This will return all exchange rates in terms of USD. Declare an async function fetchRates where we will fetch the exchange rates from the API. Use the fetch function with a await keyword to fetch the API URL. Use the json method of the Response interface to parse the response into a JavaScript object. Set the value of the rates object to the response object's rate property. Now call the populateOptions function, which we are going to write next.

Fetching Exchange Rates

Declare an empty string variable val, which will have some HTML code containing <option> elements for the dropdown. Use the Object.keys method on the rates object, which will return an array containing all the keys. We will iterate over this array using forEach. Create a variable htmlString to hold the HTML string. Create an <option> element with its value attribute set to the currency code, which is the code argument. The text inside the element will also be the same. Concatenate this string to the val variable. Now set the innerHTML of both select elements by iterating over the array returned by querySelectorAll.

Converting Currency

Let's write a convert function where we will convert one value from one currency to another. It will take three arguments: value, initial currency, and target currency. The formula for conversion is value / rate of initial currency * rate of target currency. For simplicity, we will round the decimal to three places using the toFixed method. Since there are some currencies whose values are too small, we will check if the rounded value equals zero. If it does, we will return the original value rounded to five decimal places. Else, we will return the value rounded to three decimal places.

Displaying Converted Rates

Let's write a displayRate function which will display the converted rate for a unit currency. Get the values from both select elements. Use the convert function to convert unit currency from v1 to v2. Set the innerHTML for .rate1 and .rate2 elements as follows. Be sure to use backticks in order to use template literals. Add a click event listener to the result button. Get the currency code of the currency that has to be converted using the first select element. Get the value from the first input and pass it to parseFloat. Get the currency code of the target currency using the second select element. If the input's value is none, we will alert the user to enter a number. Else, we will convert the value using our convert function. Set the value of the second input to the converted value. Add a change event listener to both select elements to execute the displayRate function so that the rates change when the user changes the currencies.

Swapping Values

Let's add a click event listener to the swap icon to swap the values of dropdowns and inputs. Get the values of both inputs and select elements. Set the value of the second input to the value of the first input. Set the value of the first input to the value of the second input. Do the same with the select elements. Lastly, call the displayRate function to update the rates on the screen. Now call the fetchRates function and we are good to go. Here our project is ready. Let's see the preview. It is working as expected.

Conclusion

In this tutorial, we have learned how to create a currency converter using JavaScript. We started by setting up the HTML file and including the necessary CSS and JavaScript files. We fetched exchange rates from an API and populated the dropdown options. We created functions to convert currency values and display the converted rates. We also added a feature to swap the input values. Feel free to customize the converter according to your needs. Thank you for following along!

Highlights

  • Create a currency converter using JavaScript
  • Fetch exchange rates from an API
  • Populate dropdown options
  • Convert currency values
  • Display converted rates
  • Swap input values

FAQ

Q: Can I convert any currency using this converter? A: Yes, you can convert any currency as long as it is included in the exchange rates fetched from the API.

Q: Can I customize the appearance of the converter? A: Yes, you can modify the CSS code to change the colors, fonts, and layout of the converter.

Q: Can I add more currencies to the dropdown options? A: Yes, you can edit the populateOptions function to include additional currencies in the dropdown.

Q: Does this converter update the exchange rates automatically? A: No, the exchange rates are fetched only once when the page loads. You can add a refresh button to update the rates manually.

Q: Can I use this converter on my website? A: Yes, you can copy the HTML, CSS, and JavaScript code and adjust it to fit your website.

I am a shopify merchant, I am opening several shopify stores. I use ppspy to find Shopify stores and track competitor stores. PPSPY really helped me a lot, I also subscribe to PPSPY's service, I hope more people can like PPSPY! — Ecomvy

Join PPSPY to find the shopify store & products

To make it happen in 3 seconds.

Sign Up
App rating
4.9
Shopify Store
2M+
Trusted Customers
1000+
No complicated
No difficulty
Free trial