- Saved searches
- Use saved searches to filter your results more quickly
- poliweb/converter-currency
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Конвертер валют на JavaScript
- Основы создания:
- Как сделать конвертер валют в JavaScript:
- Вывод:
- How to create currency converter in javascript
- Currency Converter Using JavaScript Step By Step Guide
- Step:#1
- Step:#2
- Currency converter in javascript video output:
- Currency Converter With Javascript
- Video Tutorial:
- Project Folder Structure:
- HTML:
- Currency Converter
- CSS:
- Javascript:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A simple JavaScript exchange rate converter. Gets up-to-date USD, EUR, GPB rate data. Converts ruble to dollars, euros and British pounds. Displays the result based on the amount entered.
poliweb/converter-currency
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Простой конвертёр курса валют на JavaScript.
Получает актуальные данные курса USD, EUR, GPB. Конвертирует рубль в доллары, евро и британские фунты. Выводит результат на основании введенной суммы.
About
A simple JavaScript exchange rate converter. Gets up-to-date USD, EUR, GPB rate data. Converts ruble to dollars, euros and British pounds. Displays the result based on the amount entered.
Конвертер валют на JavaScript
В этой статье я расскажу как сделать на js конвертер валюты, думаю будет очень интересно и полезно, особенно тем кто реализует RestAPI, так как это может уменьшить нагрузку на ваш сервер.
Мы уже делали конвертер валют, но на PHP, что узнать как это сделать, прочитайте эту статью «Как добавить курс и конвертер валют на PHP».
Основы создания:
Начнём с основ создания, то есть сделаем HTML файл в котором будем выводить нынешний курс, для этого создадим файл «index.html», вот что в нём должно быть.
Тут не чего особо говорить, разве что в тег span мы будем выводить сколько сейчас стоит валюта.
Теперь создадим файл «script.js», там будет весь основной код, так же для получения данных, мы будем использовать библиотеку axios.js, подключим её через CDN.
Дальше переходим во файл «script.js» в нём берём все элементы которые нам нужны и получаем данные из удалённого сервера, выводим их в HTML, вот код:
Вот что должно у вас получиться:
Как видите всё работает, мы в начали берём элементы куда будем выводить стоимость одного евро и доллара, потом создаём объект где будем хранить валюту.
Потом отправляем GET запрос и в ответе получаем объект со всеми данными о валютах, ложим нужные валюты в наш объект и выводим данные.
Таким образом мы получили всё что нам нужно.
Как сделать конвертер валют в JavaScript:
Теперь сделаем полноценный конвертер валют, будем вводить число валюты и конвертировать в рубли, для это в начале сделаем в HTML инпут.
Теперь дополним наш JavaScript файл, вот что мы в нём сделаем:
В начали тут всё примерно так же как и в первом варианте, разве что ещё берём несколько элементов, это для вывода конвертированной валюты в рубли и поля для ввода этой валюты.
Потом мы начинаем отслеживать событие изменение полей, внутри проверяем, если в поле введено не число, то выводим ошибку, иначе если пустая строка, то выводим ноль, иначе выводим конвертированную валюту в рубли, так делаем с евро и долларом.
Так же при выводе мы округляем получившееся число, для лучшего понимания, вот что в итоге вышло:
Вы сможете сами проверить как всё работает, я оставлю код для скачивания.
Вывод:
В этой статье вы прочитали как сделать на js конвертер валюты, думаю вам было интересно и полезно.
How to create currency converter in javascript
A currency converter is a software, that is designed to convert a currency into another to check its corresponding value. They do so by connecting to a database of current currency exchange value.
Click here to Know more
Currency Converter Using JavaScript Step By Step Guide
To make a currency converter in javascript we use frankfurter API this is an open-source, simple, and lightweight API for current and historical foreign exchange (forex) rates published by the European Central Bank.
First, we need to create two files index.html and style.css then we need to do code for it.
Step:#1
Add below code inside index.html
lang="en"> charset="UTF-8" /> How to create currency converter name="viewport" content="width=device-width, initial-scale=1.0" /> http-equiv="X-UA-Compatible" content="ie=edge" /> rel="stylesheet" href="style.css" /> href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet"> rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> class="currency-row-outer"> class="currency-converter"> Currency Converter class="field grid-50-50"> class="colmun col-left"> type="number" class="form-input" id="number" placeholder="00000"> class="colmun col-right"> class="select"> name="currency" class="currency" onchange="updatevalue()"> class="field grid-50-50"> class="colmun col-left"> type="text" class="form-input" id="output" placeholder="00000" disabled> class="colmun col-right"> class="select"> name="currency" class="currency" onchange="updatevalue()"> const select = document.querySelectorAll('.currency'); const number = document.getElementById("number"); const output = document.getElementById("output"); fetch('https://api.frankfurter.app/currencies').then((data) => data.json()) .then((data) => display(data); >); function display(data) const entries = Object.entries(data); for (var i = 0; i entries.length; i++) select[0].innerHTML += `$entries[i][0]>">$entries[i][0]> : $entries[i][1]> `; select[1].innerHTML += `$entries[i][0]>">$entries[i][0]> : $entries[i][1]> `; > > function updatevalue() let currency1 = select[0].value; let currency2 = select[1].value; let value = number.value; if (currency1 != currency2) convert(currency1, currency2, value); > else alert("Choose Diffrent Currency"); > > function convert(currency1, currency2, value) const host = "api.frankfurter.app"; fetch(`https://$host>/latest?amount=$value>&from=$currency1>&to=$currency2>`) .then((val) => val.json()) .then((val) => console.log(Object.values(val.rates)[0]); output.value = Object.values(val.rates)[0]; >); >
Step:#2
Then we need to add code for style.css which code I provide in the below screen.
/*Start Currency Converter*/ * padding: 0; margin: 0; font-family: 'IBM Plex Sans', sans-serif; > body height: 100vh; width: 100vw; overflow-x: hidden; > .currency-row-outer display: flex; align-items: center; justify-content: center; height: 100%; > .currency-converter width: 100%; max-width: 480px; text-align: center; > input, select color: #363636; font-size: 1rem; height: 2.3em; border-radius: 4px; max-width: 100%; width: calc(100% - 15px); margin: auto; outline: 0; background: #fff; border-color: #dbdbdb; padding-left: 15px; border: 1px solid #00000057; box-shadow: inset 0 0.0625em 0.125em rgb(10 10 10 / 5%); -webkit-appearance: none; > .field.grid-50-50 display: grid; grid-template-columns: 1fr 1fr; grid-gap: 15px; > .currency-converter .colmun margin-bottom: 15px; > select.currency border-color: #3273dc; width: 100%; height: 100%; cursor: pointer; font-size: 1em; max-width: 100%; outline: 0; display: block; > .currency-converter .select position: relative; height: 100%; > h2 padding-bottom: 30px; > .currency-converter .select:after transform: rotate(-45deg); transform-origin: center; content: ""; border: 3px solid rgba(0, 0, 0, 0); border-radius: 2px; border-top: 0; border-right: 0; display: block; height: 0.525em; width: 0.525em; z-index: 4; position: absolute; top: 50%; right: 1.125em; margin-top: -0.4375em; > .select:not(:hover)::after border-color: #3273dc; > .select:hover::after border-color: #363636; >
Currency converter in javascript video output:
Currency Converter With Javascript
Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn Javascript. So in today’s tutorial let us expand our javascript knowledge with a fun and easy-to-build project called ‘Currency Converter’. To build this project we need HTML, CSS, and Javascript.
Video Tutorial:
For a better understanding of how we built the functionality of this project, I would advise you to watch the video below. If you find the video helpful give it a like and subscribe to my YouTube channel where I post new tips, tricks, and tutorials related to HTML, CSS, and Javascript.
Project Folder Structure:
Let’s build the project folder structure before we begin writing the code. We create a project folder called ‘Currency Converter’. Inside this folder, we have index.html, style.css, script.js, currency-codes.js, API-key.js, and SVG icon files.
HTML:
We begin with the HTML Code. First, create a file called – ‘index.html’. Copy the code below and paste it into your HTML file.
Currency Converter
CSS:
Next, we style our list using CSS. For this copy, the code provided to you below and paste it into your stylesheet.
* < padding: 0; margin: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; border: none; outline: none; >body < background-color: #9873fe; >.wrapper < width: 90%; max-width: 25em; background-color: #ffffff; position: absolute; transform: translate(-50%, -50%); left: 50%; top: 50%; padding: 2em; border-radius: 0.8em; >.app-details < display: flex; align-items: center; flex-direction: column; >.app-icon < width: 9.37em; >.app-title < font-size: 1.6em; text-transform: uppercase; margin-bottom: 1em; >label < display: block; font-weight: 600; >input#amount < font-weight: 400; font-size: 1.2em; display: block; width: 100%; border-bottom: 2px solid #02002c; color: #7a789d; margin-bottom: 2em; padding: 0.5em; >input#amount:focus < color: #9873fe; border-color: #9873fe; >.dropdowns < display: flex; align-items: center; justify-content: space-between; gap: 1em; >select < width: 100%; padding: 0.6em; font-size: 1em; border-radius: 0.2em; appearance: none; -webkit-appearance: none; -moz-appearance: none; background-image: url("arrow-down.svg"); background-repeat: no-repeat; background-position: right 15px top 50%, center; background-size: 20px 20px; background-color: #9873fe; color: #ffffff; >select option < background-color: #ffffff; color: #02002c; >button < font-size: 1em; width: 100%; background-color: #9873fe; padding: 1em 0; margin-top: 2em; border-radius: 0.3em; color: #ffffff; font-weight: 600; >#result
Javascript:
Finally, we add functionality using Javascript. Once again copy the code below and paste it into your script file.
Before moving to actual implementation we store the API key in the file ‘api-key.js’ and store all the currency codes in the ‘currency-codes.js’ file.
Then let’s move on to the implementation steps:
- Create initial HTML references and store the API URL in a variable
- Fill Currency codes in dropdown options
- When the user clicks on the convert button or when the page loads we call the ‘convertCurrency’ function
- The ‘convertCurrency’ function stores the values of both the dropdowns that the user has chosen or based on default values
- Now if the user hasn’t submitted a blank amount we make a GET request to the API URL using the ‘fetch’ method.
- The API returns current rates for each currency
- Now we convert the entered amount to another currency using the fetched rate and display it upto two decimals
let api = `https://v6.exchangerate-api.com/v6/$/latest/USD`; const fromDropDown = document.getElementById("from-currency-select"); const toDropDown = document.getElementById("to-currency-select"); //Create dropdown from the currencies array currencies.forEach((currency) => < const option = document.createElement("option"); option.value = currency; option.text = currency; fromDropDown.add(option); >); //Repeat same thing for the other dropdown currencies.forEach((currency) => < const option = document.createElement("option"); option.value = currency; option.text = currency; toDropDown.add(option); >); //Setting default values fromDropDown.value = "USD"; toDropDown.value = "INR"; let convertCurrency = () => < //Create References const amount = document.querySelector("#amount").value; const fromCurrency = fromDropDown.value; const toCurrency = toDropDown.value; //If amount input field is not empty if (amount.length != 0) < fetch(api) .then((resp) =>resp.json()) .then((data) => < let fromExchangeRate = data.conversion_rates[fromCurrency]; let toExchangeRate = data.conversion_rates[toCurrency]; const convertedAmount = (amount / fromExchangeRate) * toExchangeRate; result.innerHTML = `$$ = $$`; >); > else < alert("Please fill in the amount"); >>; document .querySelector("#convert-button") .addEventListener("click", convertCurrency); window.addEventListener("load", convertCurrency);
//Paste your generated api Key here let apiKey = "";
Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the ‘Download Code’ button below.