Comparte

Bienvenido a este proyecto divertido y práctico en el que crearemos una calculadora que convierta Bitcoin a USD. Aprenderá sobre la obtención de datos mediante API, la manipulación del DOM y el almacenamiento local, y utilizará algunas matemáticas básicas en el proceso.

Al final de este tutorial, tendrá una calculadora de precios de Bitcoin en funcionamiento que obtiene el precio actual de Bitcoin, le permite calcular el valor de sus tenencias de Bitcoin y guarda sus datos localmente.

Este es un proyecto ideal para principiantes que entienden los conceptos básicos de HTML, CSS y JavaScript.

Esto es lo que crearemos:

Captura de pantalla: 17 de julio de 2024 a las 21.39.30
¡El proyecto terminado!

Configuración del proyecto

Crea una nueva carpeta y nómbrala con un nombre que sea relevante para el proyecto, como btc-usd-calc . Crea un archivo con el título index.html en la carpeta del proyecto.

Comience por escribir el HTML. La página debe contener básicamente

  • Un encabezado
  • El precio actual de Bitcoin
  • Un campo de texto para que el usuario ingrese sus tenencias de Bitcoin
  • Un botón para calcular sus tenencias de Bitcoin
  • La cantidad calculada
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Bitcoin Calculator</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <div class="container">
      <h1>Bitcoin Calculator</h1>
      <main id="main">
        <p>
          <span id="currentPrice">Latest price:</span>
          <b>$<span id="bitcoinPrice"></span> USD</b>
        </p>
        <label for="bitcoinAmount">How much Bitcoin do you own?</label>
        <input type="number" id="bitcoinAmount" step="any" placeholder="0.05" />
        <button id="calculateBtn">Calculate</button>
        <br />
        <br />
        <h3 id="usdAmount"></h3>
      </main>
    </div>
    <script src="script.js"></script>
  </body>
</html>

Ábrelo en un navegador y deberías ver esto:

Captura de pantalla: 2024-07-17-a-las-21.44.38
Bastante básico por el momento, ¡el estilo se hará más tarde!

Obtener la API

Ahora, en el mismo directorio que index.html , crea un nuevo archivo titulado script.js .

Es importante saber qué API utilizar. Te recomiendo que utilices esta mientras sigues este tutorial. La API de CoinDesk es:

  • Gratis
  • Rápido
  • No se necesita token API
  • Mínimo
  • Contiene la información necesaria para este proyecto.

En script.js , defina una constante para la URL de la API:

const API_URL = "https://api.coindesk.com/v1/bpi/currentprice.json";

El siguiente paso es agregar un detector de eventos para llamar a la API una vez que se cargue el contenido de la página. Puedes hacerlo agregando el siguiente código directamente debajo de la constante API_URL:

document.addEventListener("DOMContentLoaded", async () => {
  // Run an asynchronous function once the DOM content has loaded
  let bitcoinPrice; // Initialize the variable

  try {
    const response = await fetch(API_URL);
    // Await a response from the HTTP request sent to the API URL

    const data = await response.json();
    // Await the json content of the response

    bitcoinPrice = data.bpi.USD.rate_float.toFixed(2);
    // Reassign the bitcoinPrice variable to the USD value of Bitcoin, rounded to the nearest 2 decimal places.
  } catch {
    console.log("error!"); // In case of error
  }

  console.log(bitcoinPrice); // Log the price in the console
});

En caso de que se produzca algún error, el programa nos lo hará saber en la consola. De lo contrario, bitcoinPricese registrará en la consola. ¡Puedes probarlo ahora y ver si obtienes el precio actual de Bitcoin!

Cómo implementar localStorage

Básicamente, localStoragees una característica presente en la mayoría de los navegadores web (ver qué versiones la soportan aquí ) que guarda información para que se conserve en la memoria del navegador incluso después de cerrar la página o el navegador.

Comencemos editando algunas líneas:

document.addEventListener("DOMContentLoaded", async () => {
  let bitcoinPrice = localStorage.getItem("lastBitcoinPrice");
  // Retrieve the last stored Bitcoin price from localStorage, if it exists
  // Note: It should be null the first time you try running the page

  try {
    const response = await fetch(API_URL);
    const data = await response.json();
    bitcoinPrice = data.bpi.USD.rate_float.toFixed(2);
    // bitcoinPrice will be re-written
    
    localStorage.setItem("lastBitcoinPrice", bitcoinPrice);
    // Save most recent price to localStorage
  } catch {
    console.log("error!");
  }

  console.log(bitcoinPrice);
});

Cómo implementar la manipulación del DOM

El modelo de objetos de documento (DOM) es una interfaz que permite programar interacciones con documentos web. Básicamente, la manipulación del DOM con JavaScript nos permite actualizar ciertas partes o la totalidad de un documento.

En este proyecto, lo usaremos para mostrar el precio actual de Bitcoin y el valor calculado. También lo usaremos para recuperar el valor ingresado por el usuario en el #bitcoinAmountcampo de texto cuando se hace clic en el botón Calcular.

Implementemos la manipulación del DOM:

document.addEventListener("DOMContentLoaded", async () => {
  const main = document.getElementById("main");
  const bitcoinPriceElement = document.getElementById("bitcoinPrice");
  const bitcoinAmountInput = document.getElementById("bitcoinAmount");
  const calculateBtn = document.getElementById("calculateBtn");
  const usdAmountElement = document.getElementById("usdAmount");

  let bitcoinPrice = localStorage.getItem("lastBitcoinPrice");

  try {
    const response = await fetch(API_URL);
    const data = await response.json();
    bitcoinPrice = data.bpi.USD.rate_float.toFixed(2);
    localStorage.setItem("lastBitcoinPrice", bitcoinPrice);

    bitcoinPriceElement.textContent = bitcoinPrice;
    // Set the text content of bitcoinPriceElement to the current bitcoinPrice
  } catch {
    if (bitcoinPrice) {
      // If there's an existing bitcoinPrice in localStorage...
      bitcoinPriceElement.textContent = bitcoinPrice;
      // ...display whatever is saved localStorage
    } else {
      main.innerHTML = "<p>Could not fetch Bitcoin price :(</p>";
      return;
    }
  }

  console.log(bitcoinPrice);
});

Cómo calcular el valor actual de la billetera

Ahora bien, el objetivo de una calculadora de Bitcoin es calcular cuánto vale la billetera de Bitcoin de alguien, no necesariamente cuánto es el precio actual.

Por ejemplo, el precio actual de Bitcoin podría ser de 60 000 USD. Si tienes 2 Bitcoins, tu billetera está valuada en 120 000 USD. Si tienes medio (0,5) Bitcoin, tu billetera está valuada en 30 000 USD.

Obtengamos la cantidad de Bitcoin que posee el usuario ( bitcoinAmount) de localStorage.

// continue after console.log(bitcoinPrice);

let bitcoinAmount = localStorage.getItem("bitcoinAmount");

Calcula el monto en USD con esta función:

const calculateUSDAmount = () => {
  bitcoinAmount = bitcoinAmountInput.value || 0;
  // bitcoinAmount will be reassigned to whatever is in the input on the front end, otherwise it's default value will be zero

  const usdAmount = bitcoinAmount * bitcoinPrice;
  // Say you have 2 Bitcoins and the price is 60000.
  // 2 * 60000 = 120000

  usdAmountElement.innerHTML = `<b>$${usdAmount.toFixed(
    2
  )} USD</b> worth of Bitcoin.`;
  // Round it to the nearest 2 decimals and display it
};

¿Recuerdas cuando obtuvimos bitcoinAmountlocalStorage? Ahora, cuando se cargue la página, establezcamos el valor de la entrada en el front-end en bitcoinAmount.

  if (bitcoinAmount) {
    bitcoinAmountInput.value = bitcoinAmount;
    // Set the input's value to bitcoinAmount

    calculateUSDAmount();
    // Calculate and update the front-end
  }

Para que el usuario actualice su bitcoinAmount, agreguemos un detector de eventos cuando calculateBtnse hace clic en :

  calculateBtn.addEventListener("click", () => {
    localStorage.setItem("bitcoinAmount", bitcoinAmountInput.value);
    // Save the input value to localStorage

    calculateUSDAmount();
    // Calculate and update the front-end
  });

Ahora todo el JavaScript debería estar completo.

Código JavaScript completo

Todo el código debería ser similar a esto (aparte de los comentarios y el formato):

const API_URL = "https://api.coindesk.com/v1/bpi/currentprice.json";

document.addEventListener("DOMContentLoaded", async () => {
  const main = document.getElementById("main");
  const bitcoinPriceElement = document.getElementById("bitcoinPrice");
  const bitcoinAmountInput = document.getElementById("bitcoinAmount");
  const calculateBtn = document.getElementById("calculateBtn");
  const usdAmountElement = document.getElementById("usdAmount");

  let bitcoinPrice = localStorage.getItem("lastBitcoinPrice");

  try {
    const response = await fetch(API_URL);
    const data = await response.json();
    bitcoinPrice = data.bpi.USD.rate_float.toFixed(2);
    localStorage.setItem("lastBitcoinPrice", bitcoinPrice);

    bitcoinPriceElement.textContent = bitcoinPrice;
    // Set the text content of bitcoinPriceElement to the current bitcoinPrice
  } catch {
    if (bitcoinPrice) {
      // If there's an existing bitcoinPrice in localStorage...
      bitcoinPriceElement.textContent = bitcoinPrice;
      // ...display whatever is saved localStorage
    } else {
      main.innerHTML = "<p>Could not fetch Bitcoin price :(</p>";
      return;
    }
  }

  console.log(bitcoinPrice);

  let bitcoinAmount = localStorage.getItem("bitcoinAmount");

  const calculateUSDAmount = () => {
    bitcoinAmount = bitcoinAmountInput.value || 0;
    // bitcoinAmount will be reassigned to whatever is in the input on the front end, otherwise it's default value will be zero

    const usdAmount = bitcoinAmount * bitcoinPrice;
    // Say you have 2 Bitcoins and the price is 60000.
    // 2 * 60000 = 120000

    usdAmountElement.innerHTML = `<b>$${usdAmount.toFixed(
      2
    )} USD</b> worth of Bitcoin.`;
    // Round it to the nearest 2 decimals and display it
  };

  if (bitcoinAmount) {
    bitcoinAmountInput.value = bitcoinAmount;
    // Set the input's value to bitcoinAmount

    calculateUSDAmount();
    // Calculate and update the front-end
  }

  calculateBtn.addEventListener("click", () => {
    localStorage.setItem("bitcoinAmount", bitcoinAmountInput.value);
    // Save the input value to localStorage
  
    calculateUSDAmount();
    // Calculate and update the front-end
  });
});

¡Pruébalo en el navegador y juega con él!

Captura de pantalla: 18 de julio de 2024 a las 13.11.56

Cómo añadir algo de estilo

En este momento, no hay CSS, por lo que parece bastante básico. Puedes personalizar el estilo según tus preferencias.

Si quieres darle el estilo que yo hice, continúa agregando esta línea en la parte inferior <head>:

   <link rel="stylesheet" href="style.css" />
</head>

Luego, crea un nuevo archivo titulado style.css dentro del mismo directorio que index.html .

Escriba el siguiente código en style.css :

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap");

body {
  font-family: "Inter", sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;
}

.container {
  max-width: 50rem;
  margin: 5rem auto;
  background-color: #fff;
  padding: 2rem;
  border-radius: 1rem;
  box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1);
}

#main {
  width: 50%;
  margin: auto;
}

h1 {
  text-align: center;
  font-size: 3rem;
  margin-bottom: 2rem;
  background-image: linear-gradient(to right, #4b0bff, #68b2ff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

h3 {
  font-weight: normal;
}

button {
  padding: 0.5rem 0.75rem;
  border: none;
  background-color: #007bff;
  color: #fff;
  cursor: pointer;
  border-radius: 0.5rem;
  transition: 0.3s;
  margin-left: 0.25rem;
}

button:hover {
  background-color: #0056b3;
}

label {
  display: block;
  margin-bottom: 1rem;
}

input[type="number"] {
  padding: 0.5rem;
  font-size: 1rem;
  border: none;
  background-color: #e3e3e3;
  border-radius: 0.5rem;
}

@media (prefers-color-scheme: dark) {
  body {
    color-scheme: dark;
    color: white;
    background: #2b0057;
  }

  h1 {
    background-image: linear-gradient(to right, #4facfe, #00f2fe);
  }

  .container {
    background: #16022c;
  }

  input[type="number"] {
    background-color: #33194d;
  }
}

Deberías ver esto si estás en modo oscuro:

Captura de pantalla: 2024-07-18-a-las-13.17.06
Modo oscuro

Y esto si estás en modo claro:

Captura de pantalla: 2024-07-18-a-las-13.16.52
Modo claro

¡Y eso es todo!

Siéntete libre de revisar miLinkedIn o GitHub .

Si desea comunicarse conmigo, mi dirección de correo electrónico es sistemas@torrezinfor.com