BlogsPage
  • Home
  • Tech
  • Code
  • Web
  • Visual Stories
  • About
  • Contact
No Result
View All Result
  • Home
  • Tech
  • Code
  • Web
  • Visual Stories
  • About
  • Contact
No Result
View All Result
Blogspage
No Result
View All Result
Home Code

Master the DOM and APIs by Building a Currency Converter App

currency Converter App

This article simplifies the process of creating a Currency Converter App using vanilla JavaScript. It’s well known that building more projects and practicing consistently is the key to mastering JavaScript. This Currency Converter App is developed using HTML, CSS, and vanilla JavaScript, making it perfect for beginners.

By completing this app, you’ll gain valuable insights into working with APIs, DOM manipulation, and JavaScript objects.

Let’s dive into the project and start building your own Currency Converter App!

Table of Contents

Toggle
  • Project Outline
      • About currency.js file
  • The load event on Currency Converter App
      • 1. load even on window
      • 2. loop the <select> tags
      • 3. createElement(“option”)
  • The Change Event – Currency Converter App
      • 1. Loop the <select> and use If..
      • 2. Store values in variable
      • Why Use parentElement?
      • Using Country Flag API in the Currency Converter App
  • The click event and Run API
      • 1. click event
      • 2. Run API
          • Fetching the Exchange Rate in the Currency Converter App
      • 3. Displaying the Converted Currency in the Currency Converter App

Project Outline

I have devided this project in 3 main parts which are actually the 3 main events happening in the project while user interact with the currency converter application.

Creating beautiful UI ineterface is also a challange, this is simple javascript project where API used and helped user to get the currency converion handy

This project contains below mentioned files

  • index.html
  • style.css
  • script.js
  • currency.js
  • 3 image files(currency-from flag, currency-to flag, background)

About currency.js file

In this Currency Converter App project, we’re loading currency and country data from a separate JavaScript file, where I’ve created an object as shown in the image below:

currency.js in currency converter app
currency.js

As mentioned above, the countryList object contains a list of currencies as keys, and each key holds an array that includes the country abbreviation and the full country name.

We need this information to work with the API, as it requires the currency codes and country abbreviations to fetch accurate exchange rate results for the Currency Converter App.

You can download all code from below mentioned link:

Currency Converter App – Github

The load event on Currency Converter App

The load event is the very first step in our Currency Converter App project. It triggers several internal functions that set up the initial structure and functionality of the app. Let’s explore each of these in detail.

1. load even on window

As you can see into UI there are two drop down to select the currency-from and currency to. While window loads need to apply the load events on window and load all country, currency data into the <options> tag for both select.

The load event will be like below:

window.addEventListener("load", function(){

//loop both select tags 

//initiate the loop and create new DOM element called options

//assign the values and attribute to each created element

});

By completion of load event, each <select> contained the

2. loop the <select> tags

Here, you need to select all <select> tags with querySelectorAll and assign that to the variable, as example below.

const dropDown = document.querySelectorAll("select");

You need to run one loop on dropdown and inside one more loop which will be the length of object keys, here we are refering the object – countryList.

window.addEventListener("load", function(){
    dropDown.forEach((select)=>{
        for(let i=0; i<Object.keys(countryList).length; i++)
        {
        }
      });
    });

The first forEach loop runs twice because we have two <select> elements in our Currency Converter App. Inside it, the inner for loop runs 159 times—once for each currency key in the countryList object.

We use Object.keys(countryList) to create an array of all the object’s keys, and then use the .length property to determine how many times the loop should run.

3. createElement(“option”)

As we’ve seen, the inner for loop runs 159 times for each <select> element. Since we have two <select> elements in our Currency Converter App, the inner loop runs a total of 159 × 2 = 318 times.

During each iteration, a new <option> element is created and added to the dropdown. The overall flow of this loop works as follows:

  1. CreateElement option
  2. assign the value to created element
  3. setAttribute to the new created elements
    • name attribute to set country abbreviation.
    • cname attribute to set the country name
  4. Append the new created element to select.

Below mentioned is the code of load event.

const dropDown = document.querySelectorAll("select");
window.addEventListener("load", function(){
    dropDown.forEach((select)=>{
        for(let i=0; i<Object.keys(countryList).length; i++)
        {
            // Create new DOM element 'options'
            const newElement = document.createElement("option");
            newElement.value = Object.keys(countryList)[i];
            newElement.textContent = Object.keys(countryList)[i];
            newElement.setAttribute("name", Object.values(countryList)[i][0]);
            newElement.setAttribute("cname", Object.values(countryList)[i][1]);
            select.append(newElement);

            // Logic to set the default options in dropdown
            if(newElement.value ==="INR" && select.getAttribute("name")=="currency-from")
            {
                newElement.selected = true;
            }
             if(newElement.value ==="USD" && select.getAttribute("name")==="currency-to")
            {
                newElement.selected = true;
            }
        }
    })
})

As mentioned in the Currency Converter App code above, I’ve used two if statements to set the default selected values in the dropdowns—one for each <select> element, since the app includes two currency selection menus.

The Change Event – Currency Converter App

We apply the change event to each <select> element in the Currency Converter App to perform two main tasks:

  1. Retrieve the value and attributes of the selected <option>.
  2. Update the country flag based on the selected currency.

1. Loop the <select> and use If..

We need to loop through both <select> elements to detect any changes in the dropdowns. Using the change event, we can easily identify which dropdown was modified by accessing e.target.

After retrieving the e.target value, we compare the name attribute of the changed <select> element with the existing ones. Based on this comparison, we use if statements to perform the appropriate actions for each dropdown.

The code as below:

dropDown.forEach((select)=>{
   select.addEventListener("change", (e)=>{
    if(e.target.getAttribute("name")==="currency-from")
    {
       //retrive the value and attributes of selected and store it i variable
    }

    if(e.target.getAttribute("name")==="currency-to")
    {
      //retrive the value and attributes of selected and store it i variable

    })
  
})

2. Store values in variable

In the above Currency Converter App code, we have two if statements. The first one targets the <select> element with the name attribute set to "currency-from", and the second one handles the element with the name attribute set to "currency-to".

Since we’ve already loaded the <option> elements and set their values and attributes, the structure now looks like this:

option element values
<select> tag element and its value

The values we will capture into variable as below:

currencyFrom =  e.target.value;

countryFrom = e.target.options[e.target.selectedIndex].getAttribute("name");

const cNameFrom = e.target.options[e.target.selectedIndex].getAttribute("cname");
  • currencyFrom – This variable stores the value of the selected <option>—for example: "AED".
  • countryFrom = e.target.options[e.target.selectedIndex].getAttribute(“name”);
    • e.target.options retrieves all <option> elements within the selected <select>.
    • e.target.selectedIndex returns the index of the selected option. For example, if the user selects "AED" (the first option), the index will be 0.
    • .e.target.options[0] accesses that specific <option> element.
    • .getAttribute("name") fetches the value of the name attribute from the selected <option>. For example: "AE".
  • cNameFrom -This variable stores the full country name of the selected option—for example: "United Arab Emirates".

Just like the logic above, the same approach is applied in the second if statement to retrieve the values of the following variables:

  • currencyTo – the selected currency value (e.g., "INR")
  • countryTo – the country abbreviation (e.g., "IN"),
  • cNameTo – the full country name (e.g., "India").

The complete code of change event will be looks like below:

Change event code
Change event code

In the above code of the Currency Converter App, we have also set the textContent to <h3> tag which shows the country name.

Why Use parentElement?

In the Currency Converter App, we use select.parentElement to access the parent DOM element of the <select> tag. This is useful when we want to perform additional DOM operations relative to the <select> element’s position in the layout.

By retrieving the parent element, we can easily target and manipulate sibling elements—such as updating the flag image next to the dropdown—without needing to use complex selectors or global queries.

Using Country Flag API in the Currency Converter App

It’s very easy to use a Country Flag API to dynamically display flags in the Currency Converter App. The API returns the URL of the flag image, which we can directly assign to the src attribute of the existing <img> tag next to the dropdown.

Here’s an example API URL:

https://flagsapi.com/IN/flat/64.png

To make this dynamic, we simply replace the "IN" part of the URL with the country codes we already stored in the variables countryFrom and countryTo. This allows the flags to automatically update based on the selected currencies.

select.parentElement.querySelector("img").src = `https://flagsapi.com/${countryFrom}/flat/64.png`;

Great! So far in our Currency Converter App, we’ve successfully:

  • Loaded all currencies into <option> tags,
  • Assigned values and attributes from the countryList object,
  • Retrieved the selected values and attributes using the change event,
  • Dynamically updated the flags using the Country Flag API.

Now that we have currencyFrom and currencyTo, the next step is to handle the click event and fetch the conversion rate using an external Currency Exchange API.

The click event and Run API

In this section of the code you will understand about API, DOM, how to retrive the properties and values of the object.

1. click event

We need to trigger the currency conversion when the user clicks the Convert button. To achieve this, we attach a click event listener to the button, and provide a callback function named runAPI that will handle the API request.

document.querySelector("button").addEventListener("click", runAPI);

2. Run API

We are using the currency exchange API. The link of currency exchange API is as below:
https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/

Fetching the Exchange Rate in the Currency Converter App

In the code below, we are calling the Currency Exchange API using the fetch() method. The API URL dynamically includes the currencyFrom value (converted to lowercase) as required by the endpoint format:

const result = await (await fetch(`https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@2025.4.23/v1/currencies/${currencyFrom.toLowerCase()}.json`)).json();

Explanation:

  • currencyFrom.toLowerCase() – ensures the currency code matches the API’s lowercase format.
  • .json() – converts the API response into a usable JavaScript object.
  • result – stores the full exchange data returned by the API.

We then extract the specific exchange rate from this object like so:

const exRate = result[currencyFrom.toLowerCase()][currencyTo.toLowerCase()];

exRate now holds the exact conversion rate between the selected currencyFrom and currencyTo.

3. Displaying the Converted Currency in the Currency Converter App

We use an <input> element to let users enter the amount they want to convert. The value of that input can be easily captured using the .value property:

const inputVal = document.querySelector("input").value;

Once we have the exchange rate (exRate) and the input value (inputVal), we calculate the final converted amount by multiplying both. Then, we display this result in the UI using innerText or textContent:

// Display the conversion result
document.querySelector(".output").innerText = `${inputVal} ${currencyFrom} = ${(exRate * inputVal).toFixed(2)} ${currencyTo}`;

// Display the exchange rate
document.querySelector(".ex-rate-show").textContent = `${exRate.toFixed(2)}`;

Explanation:

  • .toFixed(2) limits the result to two decimal places for better readability.
  • .output is the element where we show the final converted amount.
  • .ex-rate-show displays the raw exchange rate.

This approach ensures a clean and responsive Currency Converter App interface, giving users both the converted value and the exchange rate used.

Oh! We’ve reached the end of the article. I hope you’ve gained a solid understanding of how to create a Currency Converter App using the Fetch API 😃

🚀 Follow me on Twitter for more tips and updates : @ravindra5k

💡 Check out my other articles:

  • Everything You Need to Know About JavaScript Functions – Beginner to Pro
  • 10 Tips to Write CSS Faster and More Efficiently for New Web Developers
  • React Fiber VS Virtual DOM: How React Optimizes UI Updates
  • Type conversion VS Type coercion in JavaScript
  • JavaScript Data Types in Web Technology for Begginers
  • How to Create an Image Gallery with Filter Buttons in Just 10 Minutes!
  • Create Website Slider with HTML, CSS & Swiper.js!
1. What is a Currency Converter App?

A Currency Converter App lets users convert one currency into another using the latest exchange rates from an external API.

2. What is the difference between the change event and the click event?

The change event is triggered when the value of an input element changes, such as selecting a different option in a <select> dropdown or modifying text in an <input> field. On the other hand, the click event specifically responds to mouse clicks on an element, such as buttons, and runs the associated function when clicked.

3. How do you select the parent element in the DOM?

You can use the .parentElement property on a child element to select its parent in the DOM.

4. How do you set a name attribute to an element with a value?

You can set the name attribute using JavaScript like this:
element.setAttribute(“name”, “yourValue”);

5. How do you calculate the length of an object that contains multiple properties?

You can calculate the number of properties in an object using Object.keys() and the .length property like this:
const length = Object.keys(yourObject).length;
This returns the total number of enumerable properties (keys) in the object.

Tags: APIJavascript
Share187Tweet117Share47
Previous Post

React Components Simplified : The Complete Beginner’s Guide

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Master the DOM and APIs by Building a Currency Converter App
  • React Components Simplified : The Complete Beginner’s Guide
  • React Fiber VS Virtual DOM: How React Optimizes UI Updates
  • Everything You Need to Know About JavaScript Functions – Beginner to Pro
  • Effortlessly Create Website Slider with HTML, CSS & Swiper.js!

Recent Comments

No comments to show.

Archives

  • May 2025
  • April 2025
  • March 2025
  • January 2025

Categories

  • Code
  • CSS
  • html
  • javascript
  • Web

Categories

  • Code
  • CSS
  • html
  • javascript
  • Web

Tags

API CSS CSS3 html Javascript javascript data types react swiperjs web development
  • About
  • Advertise
  • Privacy & Policy
  • Contact

© 2025 Blogspage created by BlogsPage Developer with ❤️

No Result
View All Result
  • Home
  • Tech
  • Code
  • Web
  • Visual Stories
  • About
  • Contact

© 2025 Blogspage created by BlogsPage Developer with ❤️