DEV Community

Cover image for Create a Currency Converter with HTML, CSS, and JavaScript
oteri
oteri

Posted on • Edited on

Create a Currency Converter with HTML, CSS, and JavaScript

Have you ever been worried about what is like to know the current conversion rate of your local currency to another?
In this article, we would be creating one and how important it could be to your everyday activity.

Before we begin, you should have at least a basic understanding of using web technologies in building a mini-app for the web and mobile devices.

Prerequisite

These are some of the web skills to have before we start.

  • HTML
  • CSS
  • JavaScript
  • Working with APIs

What I built

This challenge is from the weekly dev challenge at Scrimba where we are task to build a simple currency converter that can take in values and display the result to the user through a simple to use interface.
image
check out the scrim on Scrimba.com

Getting started

HTML
HyperText Markup Language is known as the building block of any web page on the internet. We would begin the process of building our currency converter here.

First, you need to create an index.html, link the CSS and JavaScript file. We would also be making use of the input field, select, label tag, and the rest of the other blocks of code for building the markup of our final product before using CSS to style it to make it user friendly and accessible for users.

Check the index.html file.

<div class="wrapper">
        <h1>Amazing Currency Converter</h1>
        <main>
            <label for="original-currency-amount">
        Convert</label>
        <input type="number" id="original-currency-amount" placeholder="1" name="original-currency-amount"></input>


        <label for="original-currency">
            Original Currency
        </label>
        <select id="original-currency">
        </select>

        <label for="to">to</label>
        <select id="to"></select>

        <label for="exchange-rate">
        Exchange Rate:</label>

        <p id="exchange-rate"></p>

        <button id="btn" class="exchange-btn">Exchange my money now!</button>
        <p id="output-text" class="blink">
        Converted 💰 will appear here.
        </p></main>
 </div>
Enter fullscreen mode Exit fullscreen mode

CSS

With the help of CSS, we would be able to style our app when we created and wrote the markup.
Here is the look of our app with CSS.

Without CSS
image

With CSS
image

With CSS, you can make your app adaptive to various screen sizes using the media queries.

Here's the snippet of the code for styling.

@import url('https://fonts.googleapis.com/css?family=Nunito:400,700&display=swap');

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body {
  font-family: Nunito, sans-serif;
  background: #f0f0f0;
  color: #1a004e;
  font-size: 1.3rem;
}

h1 {
  font-size: 1.5rem;
  padding: 1em 0 0;
}

.wrapper {
  text-align: center;
  padding: 0.5em;
  min-height: 100vh;
}

main {
  background: #fff;
  text-align: left;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 70vh;
  margin-top: 1.5em;
  padding: 1em;
  box-shadow: 0px 1px 10px rgba(0, 0, 0, 0.15);
}

input[type='text'],
input[type='number'],
select {
  width: 100%;
  padding: 1em;
  border-radius: 0.2em;
  border: 1px solid #acacac;
  color: #1b1820;
  margin-bottom: 1em;
}

input[type='text']:focus,
button:focus {
  outline: 3px solid #acacac;
}

label {
  display: block;
  font-weight: 700;
  font-size: 1rem;
  margin-bottom: 0.5em;
}

button {
  display: block;
  width: 100%;
  padding: 1em;
  text-align: center;
  color: white;
  background: #8040ff;
  margin-top: 1.5em;
  font-weight: bold;
  font-size: 1em;
  border-radius: 0.2em;
  border: none;
}

select {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  -ms-appearance: none;
  background: url('https://www.pngrepo.com/png/155474/512/down-arrow.png');
  background-repeat: no-repeat;
  background-size: 16px 17px;
  background-position: right;
  background-origin: content-box;
  cursor: pointer;
}

.blink {
  margin-top: 1em;
  font-size: 1.5rem;
}

@media screen and (min-width: 375px) {
  h1 {
    font-size: 2rem;
  }

  label {
    font-size: 1.3rem;
  }
}

@media screen and (min-width: 768px) {
  label {
    font-size: 2rem;
  }
  input[type='number'] {
    font-size: 1.85rem;
  }
  select {
    font-size: 1.85rem;
  }

  main {
    display: flex;
    justify-content: center;
    /* align-items: center; */
  }
  main .exchange-btn {
    width: 40%;
    align-self: center;
  }
  .blink {
    align-self: center;
  }
}

@media screen and (min-width: 1024px) {
  label {
    font-size: 2.5rem;
  }
}

@media screen and (min-width: 1200px) {
  label {
    font-size: 1.5rem;
  }
}

Enter fullscreen mode Exit fullscreen mode

JavaScript

JS would help us in handling the functionality of the app. For this reason, we would use the ExchangeRate API to get real-time data. Sign up on ExchangeRate to get your API key.

JS would fetch all the sections and their values using document.getElementById selector. The changing values on selecting the amount is checked with the addEventListener command.

For the option tag, we created it using the createElement command, appended it to the each of the two select tags to fetch all the countries denomination acronyms using the Object.keys() method which returns an array of a given object's. You can read more here.

const btn = document.getElementById('btn');
const amountInput = document.getElementById('original-currency-amount');
const selectOne = document.getElementById('original-currency');
const selectTwo = document.getElementById('to');
let rate = document.getElementById('exchange-rate');
const outputText = document.getElementById('output-text');


const conversionRateURL =
  'https://v6.exchangerate-api.com/v6/[API_KEY]/latest/USD';

const from_currency = async () => {
  const res = await fetch(conversionRateURL);
  const data = await res.json();
  const rateObjects = data.conversion_rates;
  const rateArray = Object.keys(rateObjects);
  for (let i = 0; i < rateArray.length; i++) {
    const option = document.createElement('option');
    option.value = rateArray[i];
    option.innerText = rateArray[i];
    selectOne.appendChild(option);
  }
};

const to_currency = async () => {
  const res = await fetch(conversionRateURL);
  const data = await res.json();
  const rateObjects = data.conversion_rates;
  const rateArray = Object.keys(rateObjects).sort(() => Math.random() - 0.5);
  for (let i = 0; i < rateArray.length; i++) {
    const option = document.createElement('option');
    option.value = rateArray[i];
    option.innerText = rateArray[i];
    selectTwo.appendChild(option);
  }
};

const convertCurrency = async () => {
  let amount = amountInput.value;
  let from = selectOne.value;
  let to = selectTwo.value;

  const res = await fetch(
    `https://v6.exchangerate-api.com/v6/[API_KEY]/latest/${from}`
  );
  const data = await res.json();
  const rateFrom = await data.conversion_rates[to];

  outputText.textContent = `Your ${amount}${from} will currently buy you ${(
    rateFrom * amount
  ).toFixed(2)}${to}`;
  rate.innerText = `${rateFrom}${to}`;
};

from_currency();
to_currency();
btn.addEventListener('click', convertCurrency);
Enter fullscreen mode Exit fullscreen mode

Conclusion

To summarize, we have just completed our currency converter app. There is still a lot to improve upon as some edge cases should be noted when the given input for the value doesn't return an exchange rate when it is 0 or negative.
But in all, we have made a simple app that you can use to get a rate in another currency. It is worth checking out.

If this helped you in any way, kindly leave feedback, it is always welcome. I would be glad to read them and improve on working on the app to make it better.
Reach out to me on Twitter

Top comments (2)

Collapse
 
bookercodes profile image
Alex Booker

Teri, I keep seeing you pop up around Scrimba - I love that! Keep up the pace 💯

Collapse
 
terieyenike profile image
oteri

Thanks Alex