index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. async function fetchCurrency() {
  2. try {
  3. const response = await fetch(
  4. "https://api.coingecko.com/api/v3/exchange_rates"
  5. );
  6. const currency = await response.json();
  7. return currency.rates;
  8. } catch (error) {
  9. console.error(error);
  10. }
  11. }
  12. async function renderCurrency() {
  13. const currencies = await fetchCurrency();
  14. const curArray = [];
  15. for (let key in currencies) {
  16. curArray.push(key);
  17. }
  18. let firstSelect = document.querySelector("#firstSelect");
  19. for (let i = 0; i < curArray.length; i++) {
  20. let option = document.createElement("option");
  21. option.setAttribute("selected", curArray[0]);
  22. option.setAttribute("value", curArray[i]);
  23. option.innerHTML = currencies[curArray[i]]["name"];
  24. firstSelect.appendChild(option);
  25. }
  26. return currencies;
  27. }
  28. renderCurrency();
  29. async function convert() {
  30. const objCur = await renderCurrency();
  31. const curArray = [];
  32. for (let key in objCur) {
  33. curArray.push(key);
  34. }
  35. let currency1 = document.querySelector("#firstCurrency");
  36. let currency2 = document.querySelector("#secondCurrency");
  37. let value1 = document.querySelector("#firstInput");
  38. let value2 = document.querySelector("#secondInput");
  39. if (!currency1.value) {
  40. currency1.value = "btc";
  41. }
  42. if (!currency2.value) {
  43. currency2.value = "usd";
  44. }
  45. if (value1.value === "" || +value1.value < 0) {
  46. alert(
  47. "Не введено число / Введено отрицательное число\nПоставлено число по умолчанию - 1"
  48. );
  49. value1.value = 1;
  50. }
  51. if (currency1.value === currency2.value) {
  52. value2.value = value1.value;
  53. }
  54. if (currency2.value === "btc") {
  55. value2.value = objCur[currency1.value]["value"];
  56. }
  57. if (currency1.value !== currency2.value) {
  58. value2.value =
  59. (value1.value ** 2 * objCur[currency2.value]["value"]) /
  60. (value1.value / (1 / objCur[currency1.value]["value"]));
  61. }
  62. currency1.disabled = true;
  63. currency2.disabled = true;
  64. value1.disabled = true;
  65. let divButton = document.querySelector(".buttonBox");
  66. divButton.firstChild.remove();
  67. let reloadButton = document.createElement("button");
  68. reloadButton.className = "btn btn-outline-secondary btn-lg";
  69. reloadButton.innerText = "Try again";
  70. divButton.appendChild(reloadButton);
  71. reloadButton.onclick = function () {
  72. window.location.reload();
  73. };
  74. }