{}const=>[]async()letfn</>var
WebPracticeDevelopment

Currency conversion app 💰🌍

Quickly and easily convert currencies at the current rate with our convenient online converter. Choose currencies, enter the amount and get an accurate result in real time. Suitable for travel and online shopping.

К

Kodik

Author

8 min read

In this article, we will create a simple but useful web application for currency conversion using HTML, CSS, and JavaScript. This application will be useful for anyone who travels frequently or works with international transactions. At the end of the article, you will be able to run a working currency conversion application right in your browser. 🎉

Project demo | 📂 Download source code on GitHub

🤖 In the app Code you can learn HTML, CSS and JavaScript, as well as many other courses to start your journey in web development! 🌱


1. Project description ✨

Our currency conversion app will allow the user to select the currency in which they want to enter the amount and convert it to another currency at the current rate. We will use the API to get the current exchange rates. The application interface will be intuitive and simple, so that any beginner can easily understand it. 🌐


2. Preparation for the project 🛠️

To get started, we will need the following tools and resources:

  • Text editor (e.g. VS Code) for writing code.

  • Browser to test the application.

  • API for getting exchange rates. We will use the free API from Exchangerate-API, which allows you to receive up-to-date data on exchange rates. To do this, you need to register on the site and get an API key.

As soon as you have the API key, we can integrate it into our project and use it for currency conversion. 🚀


3. Development steps 🖥️

Step 1: Create HTML

HTML is the basis of our application. Using HTML, we will create a structure for entering data and displaying the result.

Here's what the main file index.html will look like:

<!DOCTYPE html>
<!-- Сделано командой coursme - https://coursme.com/ -->
<html lang="ru" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Приложение для конвертации валют | Coursme</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Ссылка на CDN для иконок FontAwesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<div class="wrapper">
  <header>Конвертер валют</header>
  <form action="#">
    <div class="amount">
      <p>Введите сумму</p>
      <input type="text" value="1">
    </div>
    <div class="drop-list">
      <div class="from">
        <p>Из</p>
        <div class="select-box">
          <img src="https://flagcdn.com/48x36/us.png" alt="flag">
          <select> <!-- Опции добавляются через JavaScript --> </select>
        </div>
      </div>
      <div class="icon"><i class="fas fa-exchange-alt"></i></div>
      <div class="to">
        <p>В</p>
        <div class="select-box">
          <img src="https://flagcdn.com/48x36/np.png" alt="flag">
          <select> <!-- Опции добавляются через JavaScript --> </select>
        </div>
      </div>
    </div>
    <div class="exchange-rate">Получение обменного курса...</div>
    <button>Получить обменный курс</button>
  </form>
</div>

<script src="js/country-list.js"></script>
<script src="js/script.js"></script>

</body>
</html>

Step 2: Styling with CSS

Now let's add some styles to make our app look neat and beautiful. Here's what the styles.css file will look like:

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #11152C;
}
::selection{
  color: #fff;
  background: #11152C;
}
.wrapper{
  width: 370px;
  padding: 30px;
  border-radius: 7px;
  background: #fff;
  box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.05);
}
.wrapper header{
  font-size: 28px;
  font-weight: 500;
  text-align: center;
}
.wrapper form{
  margin: 40px 0 20px 0;
}
form :where(input, select, button){
  width: 100%;
  outline: none;
  border-radius: 5px;
  border: none;
}
form p{
  font-size: 18px;
  margin-bottom: 5px;
}
form input{
  height: 50px;
  font-size: 17px;
  padding: 0 15px;
  border: 1px solid #999;
}
form input:focus{
  padding: 0 14px;
  border: 2px solid #11152C;
}
form .drop-list{
  display: flex;
  margin-top: 20px;
  align-items: center;
  justify-content: space-between;
}
.drop-list .select-box{
  display: flex;
  width: 115px;
  height: 45px;
  align-items: center;
  border-radius: 5px;
  justify-content: center;
  border: 1px solid #999;
}
.select-box img{
  max-width: 21px;
}
.select-box select{
  width: auto;
  font-size: 16px;
  background: none;
  margin: 0 -5px 0 5px;
}
.select-box select::-webkit-scrollbar{
  width: 8px;
}
.select-box select::-webkit-scrollbar-track{
  background: #fff;
}
.select-box select::-webkit-scrollbar-thumb{
  background: #888;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}
.drop-list .icon{
  cursor: pointer;
  margin-top: 30px;
  font-size: 22px;
}
form .exchange-rate{
  font-size: 17px;
  margin: 20px 0 30px;
}
form button{
  height: 52px;
  color: #fff;
  font-size: 17px;
  cursor: pointer;
  background: #11152C;
  transition: 0.3s ease;
}
form button:hover{
  background: #11152C;
}

Step 3: Description of JavaScript code

In our JavaScript currency conversion app, we will perform several basic tasks:

  1. Filling in drop-down lists with currencies: First, we will populate both drop-down lists (fromCurrency and toCurrency) with available currencies using the currency data provided in the country_list object. This process includes adding flags and currency codes to the lists.

  2. Processing currency selection: When a user selects a currency from one of the drop-down lists, we will automatically update the displayed flag for each currency to reflect the user's choice.

  3. Switching currencies using the icon: For the user's convenience, we will add the ability to switch currencies between the "From" and "To" fields via the currency exchange icon. When you click on the icon, the currencies will swap places.

  4. Getting the exchange rate: When you click the "Get exchange rate" button or when you change any of the currencies, the application will send a request to the external API to get the current exchange rate between the selected currencies. We will use the API from Exchangerate-APIto receive up-to-date data on exchange rates.

  5. Displaying results: After receiving the rate, we will calculate the result of converting the entered amount into the selected currency and display it on the screen. If something goes wrong (for example, there is no Internet or the API does not respond), we will show an error.

Code description and functionality

  1. Filling in drop-down lists: We will use the country_list object, which contains currency codes and their corresponding countries. Using this object, we will fill in both drop-down lists (with currencies for the "From" and "To" fields).

for (let i = 0; i < dropList.length; i++) {
    for (let currency_code in country_list) {
        let selected = i == 0 ? currency_code == "USD" ? "selected" : "" : currency_code == "NPR" ? "selected" : "";
        let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
        dropList[i].insertAdjacentHTML("beforeend", optionTag);
    }
}

Here we go through all the drop-down lists and add currencies to them. By default, the currency USD will be selected for the "From" field, and the currency NPR for the "To" field.

  1. Flag update when changing currency: When the user selects a currency, we update the flag that displays the country to which that currency belongs. To do this, we use the loadFlag method, which will change the flag image in the <img> tag:

function loadFlag(element) {
    for (let code in country_list) {
        if (code == element.value) {
            let imgTag = element.parentElement.querySelector("img");
            imgTag.src = `https://flagcdn.com/48x36/${country_list[code].toLowerCase()}.png`;
        }
    }
}
  1. Switching currencies using the icon: The user can swap currencies using the exchange icon. When you click on this icon, the currency codes in the "From" and "To" fields are swapped:

const exchangeIcon = document.querySelector("form .icon");
exchangeIcon.addEventListener("click", () => {
    let tempCode = fromCurrency.value;
    fromCurrency.value = toCurrency.value;
    toCurrency.value = tempCode;
    loadFlag(fromCurrency);
    loadFlag(toCurrency);
    getExchangeRate();
});
  1. Getting the exchange rate: When the user clicks the "Get exchange rate" button, or when he changes currencies, we make a request to the API to get the current rate. The API returns the exchange rate for the selected currencies, and we calculate the total amount:

function getExchangeRate() {
    const amount = document.querySelector("form input");
    const exchangeRateTxt = document.querySelector("form .exchange-rate");
    let amountVal = amount.value;
    if (amountVal == "" || amountVal == "0") {
        amount.value = "1";
        amountVal = 1;
    }

    const apiKey = 'f2cd93cc5c526e3204de8e90';  // Your API key
    exchangeRateTxt.innerText = "Getting the exchange rate...";

    let url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency.value}`;

    fetch(url).then(response => response.json()).then(result => {
        let exchangeRate = result.conversion_rates[toCurrency.value];
        let totalExRate = (amountVal * exchangeRate).toFixed(2);
        exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`;
    }).catch(() => {
        exchangeRateTxt.innerText = "Something went wrong";
    });
}

We make a request to the API and use the received rate to calculate the total amount. If an error occurs (for example, problems with the Internet connection), we display an error message.

Important points:

  • Preventing form submission: When you click on the "Get exchange rate" button, we prevent the standard behavior of the form (page reload) using e.preventDefault() so that all processing takes place on the same page.

  • Input validation: We check that the user has not entered 0 or an empty value in the amount field. If this happens, we use the value 1 by default.

  • API Key: The code uses an external API to get current exchange rates. You must obtain your own API key by registering at Exchangerate-APIto replace the current key in the code.

  • Flag update: We update the flag image in the <img> tag depending on the selected currency, getting the country code from the country_list object.

This approach allows you to create a flexible currency conversion application using HTML, CSS, and JavaScript, which will receive up-to-date data from an external API and provide the user with a convenient interface for converting currencies in real time.

You can download the full code on our GitHub


Conclusion ✨

Now you have a working currency converter that uses up-to-date rates from the API! You can add more currencies or improve the interface at your discretion. Don't forget that this project is ideal for beginners, as it covers all the main aspects of web development: creating an HTML structure, styling with CSS, and working with APIs using JavaScript. Good luck with your development! 🎯

For the full source code and possibly additional improvements, check out our GitHub.

If you have any questions, don't hesitate to ask. Good luck in programming, and may your projects always be as interesting and exciting! 👊🌟

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card