Тема: Переключення між валютами js
Некоректно працює конвертер валют, саме з такими проблемами я зіткнувся:
1. Мені потрібно, щоб у кожному списку було по три валюти, у першому EUR, USD, GBP, а у другому UAH, GBP, EUR, але проблема в тому, що зміна валют USD та UAH працювати не будуть, тому що вони не повторюються, як це виправити? Це треба окремо створювати масив з конкретними валютами в js коді або як?
2. За замовчуванням збоку, де показує курс, має показувати 1 USD = 36.5686 UAH, а воно за замовчуванням показує 1 EUR = 36.9965 UAH, воно бере те, що перше стоїть у блоці div, але я не хочу переставляти місцями, також воно не змінюється автоматично, тобто якщо я, припустимо, виберу EUR і GBP курс не змінитися до тих пір, поки я в інпуті не вписуватиму число, чому так?
3. Чому список, що випадає, закривається, тільки коли я його закрию? Чому він не закривається, коли я вибрав валюту чи натиснув на пусте місце?
Як виправити ці проблеми?
html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Currency Converter</title>
<link rel="shortcut icon" href="currencies-icon-10.jpg" type="image/x-icon">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="header">
<div class="indent-right"></div>
<b>Конвертор валют</b>
</div>
<div class="currency">
<div class="custom-select">
<div class="custom-select__placeholder"></div>
<div class="custom-select__list">
<div class="custom-select__option" data-value="EUR">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/EU.svg"/></div>
<div class="custom-select__option-name">EUR</div>
<div class="custom-select__option-symbol">€</div>
</div>
<div class="custom-select__option custom-select__option--select" data-value="USD">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/US.svg"/></div>
<div class="custom-select__option-name">USD</div>
<div class="custom-select__option-symbol">$</div>
</div>
<div class="custom-select__option" data-value="GBP">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/GB.svg"/></div>
<div class="custom-select__option-name">GBP</div>
<div class="custom-select__option-symbol">£</div>
</div>
<!-- <div class="custom-select__option" data-value="UAH">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/UA.svg"/></div>
<div class="custom-select__option-name">UAH</div>
<div class="custom-select__option-symbol">₴</div>
</div> -->
</div>
</div>
<input id="amount-one" placeholder="200.00" />
</div>
<div class="swap-rate-container">
<button class="btn" id="swap">
<div class="btn-arrows">
<div style="display: flex;">
<svg
height="24px"
width="24px"
version="1.1"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<g
fill="none"
fill-rule="evenodd"
stroke="none"
stroke-width="1"
>
<path d="M0 0h24v24H0z"></path>
<path
d="M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z"
fill="#000"
fill-rule="nonzero"
></path>
</g>
</svg>
</div>
</div>
</button>
<div class="rate" id="rate"></div>
</div>
<div class="currency">
<div class="custom-select">
<div class="custom-select__placeholder"></div>
<div class="custom-select__list">
<div class="custom-select__option custom-select__option--select" data-value="UAH">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/UA.svg"/></div>
<div class="custom-select__option-name">UAH</div>
<div class="custom-select__option-symbol">₴</div>
</div>
<div class="custom-select__option" data-value="GBP">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/GB.svg"/></div>
<div class="custom-select__option-name">GBP</div>
<div class="custom-select__option-symbol">£</div>
</div>
<div class="custom-select__option" data-value="EUR">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/EU.svg"/></div>
<div class="custom-select__option-name">EUR</div>
<div class="custom-select__option-symbol">€</div>
</div>
<!-- <div class="custom-select__option" data-value="USD">
<div class="custom-select__option-icon"><img src="https://cdn.privat24.ua/icons/file/US.svg"/></div>
<div class="custom-select__option-name">USD</div>
<div class="custom-select__option-symbol">$</div>
</div> -->
</div>
</div>
<input id="amount-two" placeholder="200.00" />
</div>
</div>
<script src="script.js"></script>
</body>
</html>
css.
body {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
min-height: 100vh;
margin: 0;
}
.custom-select {
display: block;
width: 150px;
border-bottom: 2px solid rgba(0, 0, 0, 0.12);
position: relative;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
z-index: 1;
margin-bottom: 8.7px;
}
.custom-select:hover {
border-bottom: 2px solid rgba(0, 0, 0, 0.54);
}
.custom-select:focus {
color: #8dc641;
}
.custom-select__list {
display: block;
border-radius: 5px;
background-color: #fff;
padding: 5px 0;
box-shadow: 0 5px 10px 0 rgba(0,0,0,0.15);
position: absolute;
z-index: 0;
left: 0;
top: calc(100% + 12px);
opacity: 0;
pointer-events: none;
transform: translateY(10px);
transition-property: transform, opacity;
transition-timing-function: ease-out;
transition-duration: 0.3s;
box-sizing: border-box;
}
.custom-select--drop .custom-select__list {
transform: translateY(0);
opacity: 1;
pointer-events: all;
}
.custom-select--drop .custom-select__placeholder::after {
transform: translateY(-50%) rotateX(180deg);
}
.custom-select__option {
display: flex;
justify-content: flex-start;
align-items: center;
padding: 0.5em 1.5em;
box-sizing: border-box;
cursor: pointer;
z-index: 0;
}
.custom-select__option-icon {
display: block;
flex-shrink: 0;
border-radius: 5px;
overflow: hidden;
margin-right: 10px;
}
.custom-select__option-icon img {
display: block;
width: 18px;
height: 15px;
max-height: 100%;
-o-object-fit: cover;
object-fit: cover;
margin: 0;
}
.custom-select__option-name {
display: block;
width: 100%;
text-transform: uppercase;
margin-right: 10px;
}
.custom-select__option-symbol {
display: block;
flex-shrink: 0;
font-weight: bold;
}
.custom-select__option:hover {
background-color: rgba(0,0,0,0.045);
}
.custom-select__option--select .custom-select__option-name {
color: #8dc641;
}
.custom-select__placeholder {
display: block;
width: 100%;
}
.custom-select__placeholder::after {
content: '';
display: block;
width: 0;
height: 0;
border: 8px solid transparent;
border-top-width: 6px;
border-bottom: 6px solid #000;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-100%);
transition-property: transform;
transition-timing-function: ease-out;
transition-duration: 0.3s;
}
.custom-select__option {
padding-right: calc(1.5em + 10px);
}
.custom-select__option:hover {
background-color: transparent;
}
.header {
display: flex;
align-items: center;
}
.indent-right {
display: flex;
width: 24px;
height: 24px;
background-image: url("https://cdn.privat24.ua/icons/file/ServiceCurrency.svg");
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
margin-right: 10px !important;
}
.btn {
display: inline-flex;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
position: relative;
width: 57px;
height: 44px;
font-size: 16px;
line-height: 1.5;
font-family: 'Open Sans', sans-serif;
font-weight: 600;
padding: 8px 16px;
border-radius: 4px;
transition-duration: 450ms;
transition-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
word-break: normal;
color: rgba(0, 0, 0, 0.54);
background: rgb(255, 255, 255);
box-shadow: rgb(0 0 0 / 12%) 0px 2px 4px 0px, rgb(0 0 0 / 12%) 0px 0px 4px 0px;
white-space: nowrap;
border-style: none;
border-width: 0px;
border-color: rgb(255, 255, 255);
margin: 0px;
cursor: pointer;
}
.btn:hover {
background-color: lightgrey;
}
.swap-rate-container .btn-arrows {
transform: rotate(90deg);
opacity: 0.54;
transition: opacity 450ms cubic-bezier(0.23, 1, 0.32, 1);
position:absolute;
z-index: 0;
font-family: 'Open Sans', sans-serif;
}
.currency {
padding: 40px 0;
display: flex;
align-items: center;
justify-content: space-between;
}
input::placeholder {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
}
.currency input {
background: transparent;
font-size: 16px;
line-height: 1.5;
text-align: right;
font-weight: 400;
color: rgba(0, 0, 0, 0.87);
border-style: none;
border-width: 0px;
border-radius: 0px;
background: transparent;
box-shadow: none;
outline: none;
width: 65%;
font-family: 'Open Sans', sans-serif;
background: transparent;
border-bottom: 2px solid rgba(0, 0, 0, 0.12);
margin-left: 15px
}
.currency input:hover {
display:block;
line-height: 1.5;
font-family: "Open Sans", sans-serif;
border-bottom: 2px solid rgba(0, 0, 0, 0.54);
}
.currency input:focus {
border-color: #8dc641;
}
/* .currency input::after {
transform: scaleX(0);
transition: transform 250ms ease-in-out;
}
.currency input::before {
transform: scaleX(0);
transition: transform 250ms ease-in-out;
}
.currency input:hover::after {
transform: scaleX(1);
}
.currency input:hover::before {
transform: scaleX(1);
} */
.select-placeholder {
background: rgb(255, 255, 255);
color: rgba(0, 0, 0, 0.38);
}
.swap-rate-container {
display: flex;
align-items: center;
justify-content: space-between;
}
.rate {
color: black;
font-size: 15px;
padding: 0 10px;
background: #E0E0E0;
line-height: var(--tl-small);
padding: 8px;
font-family: 'Open Sans', sans-serif;
border-radius: 2px;
}
input::-webkit-inner-spin-button {
display: none !important;
}
js.
const [selectOne, selectTwo] = document.querySelectorAll('.custom-select');
const [symOne, symTwo] = document.querySelectorAll('.custom-select__option-symbol')
const [currencyOne, currencyTwo] = document.querySelectorAll('.custom-select__option--select');
const amountOne = document.getElementById('amount-one');
const amountTwo = document.getElementById('amount-two');
const rates = document.getElementById('rate');
const swap = document.getElementById('swap');
function converter() {
const currency_one = selectOne.textContent.trim().slice(0, 3);
const currency_two = selectTwo.textContent.trim().slice(0, 3);
const sym_one = symOne.textContent.trim().slice(0, 3);
const sym_two = symTwo.textContent.trim().slice(0, 3);
fetch(`https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json`)
.then((res) => res.json())
.then((data) => {
data.unshift({
"txt": "Українська гривня",
"rate": 1,
"cc": "UAH"
})
currency1 = data.find(item => item.cc === currency_one);
currency2 = data.find(item => item.cc === currency_two);
rates.innerText = `1 ${sym_one} = ${(1 * currency1.rate / currency2.rate).toFixed(4)} ${sym_two}`;
amountTwo.value = (amountOne.value !== '') ? (amountOne.value * currency1.rate / currency2.rate).toFixed(2) : '';
});
}
converter();
currencyOne.addEventListener('change', converter);
amountOne.addEventListener('input', converter);
currencyTwo.addEventListener('change', converter);
amountTwo.addEventListener('input', converter);
swap.addEventListener('click', () => {
const [valueOne, valueTwo] = [selectOne, selectTwo].map(select => select.querySelector('.custom-select__option--select').dataset.value);
amountOne.value = amountTwo.value
selectOne.querySelector(`[data-value="${valueTwo}"]`).click();
selectTwo.querySelector(`[data-value="${valueOne}"]`).click();
converter();
});
[...document.querySelectorAll(".custom-select")].map(select => {
let selected = select.querySelector(".custom-select__option--select");
if (selected) {
select.dataset.value = selected.dataset.value;
const placeholder = select.querySelector(".custom-select__placeholder");
placeholder.innerHTML = "";
const pho = selected.cloneNode(true);
pho.classList.remove("custom-select__option--select");
placeholder.appendChild(pho);
}
select.querySelector(".custom-select__list").addEventListener("click", e => {
let target = e.target.closest(".custom-select__option");
if (target) {
let parent = target.closest(".custom-select");
parent.querySelector(".custom-select__option--select").classList.remove("custom-select__option--select");
target.classList.add("custom-select__option--select");
let selected = parent.querySelector(".custom-select__option--select");
parent.dataset.value = selected.dataset.value;
const placeholder = parent.querySelector(".custom-select__placeholder");
placeholder.innerHTML = "";
const pho = selected.cloneNode(true);
pho.classList.remove("custom-select__option--select");
placeholder.appendChild(pho);
}
});
select.querySelector(".custom-select__placeholder").
addEventListener("click", e => {
let target = e.target.closest(".custom-select__placeholder");
if (target) {
target.closest(".custom-select").classList.toggle("custom-select--drop");
}
});
});