Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <body>
  <header class="header">
    <div></div>
  </header>

  <main class="main">
    <article class="article">
      <section class="section">
        <!-- Section 1 -->
        <section class="relative w-full bg-white">
          <div class="absolute w-full h-32 bg-gradient-to-b from-gray-100 to-white"></div>
          <div class="relative w-full px-5 py-10 mx-auto sm:py-12 md:py-16 md:px-10 max-w-7xl">
            <h1 class="mb-1 text-4xl font-extrabold leading-none text-gray-900 lg:text-5xl xl:text-6xl sm:mb-3">
              <a href="#_">Word Search</a>
            </h1>

            <p class="text-lg font-medium text-gray-500 sm:text-2xl">
              Objetivo: Mientras se escribe buscará al hacer una pequeña pausa
              en lugar de cada vez que pulsamos una tecla.
            </p>

            <div class="w-full pb-10 mt-8 sm:mt-16">
              <input type="search" 
                     placeholder=" Search example: Fruit, Pineapple, Orange..."
                     name="search" id="input-search" class="w-full border-4 border-indigo-500/50" />
            </div>

            <div class="flex grid h-full grid-cols-12 gap-10 pb-10 mt-8 sm:mt-16">
              <div id="box-posts" class="grid grid-cols-12 col-span-12 gap-7">

              </div>
            </div>
          </div>
        </section>
      </section>
    </article>
  </main>

  <template id="news-template">
    <div class="t-box flex flex-col items-start col-span-12 overflow-hidden shadow-sm rounded-xl md:col-span-6 lg:col-span-4">
      <a href="#_" class="w-full block transition duration-200 ease-out transform hover:scale-110">
        <img class="t-img object-cover w-full shadow-sm max-h-56" src="" />
      </a>
      <div class="relative flex flex-col items-start px-6 bg-white border border-t-0 border-gray-200 py-7 rounded-b-2xl">
        <div class="bg-indigo-400 absolute top-0 -mt-3 flex items-center px-3 py-1.5 leading-none w-auto inline-block rounded-full text-xs font-medium uppercase text-white inline-block">
          <span class="t-tag"></span>
        </div>
        <h2 class="text-base font-bold sm:text-lg md:text-xl">
          <a href="#_" class="t-title"></a>
        </h2>
        <p class="t-description mt-2 text-sm text-gray-500"></p>
      </div>
    </div>
  </template>
</body>
              
            
!

CSS

              
                /* 
Styles are not important here. The example uses tailwind but the important thing is the javascript for the queries
*/
              
            
!

JS

              
                const API_URL = "https://www.thecocktaildb.com/api/json/v1/1";
const API_SEARCH = `${API_URL}/search.php`;

// Almacena un array con todos cócteles.
var cocktails = [];

// Almacena el contador para realizar petición ajax.
var sendAjaxTimer = null;

async function handleOnChangeInputUpdate(e) {
  let target = e.target;
  let search = target.value;

  if (sendAjaxTimer) {
    clearTimeout(sendAjaxTimer);
    sendAjaxTimer = null;
  }

  // Si se ha pulsado Enter, se envía de momento la consulta.
  if (event.which == 13 || event.keyCode == 13) {
    fetchCocktails(search);
  } else {
    // Añado intervalo a la cola para ejecutarse.
    sendAjaxTimer = setTimeout(() => fetchCocktails(search), 800);
  }
}

/**
 * Borra todos los nodos hijos del elemento recibido.
 */
function removeAllChildNodes(parent) {
  while (parent.firstChild) {
    parent.removeChild(parent.firstChild);
  }
}

/**
 * Actualiza el listado de cócteles.
 */
async function updateCocktailsList() {
  const list = document.getElementById("box-posts");
  const template = document.getElementById("news-template");

  // Limpio usuarios actuales de la lista.
  removeAllChildNodes(list);

  cocktails.forEach((cocktail) => {
    const row = template.content.querySelector(".t-box").cloneNode(true);

    const title = row.querySelector(".t-title");
    const tag = row.querySelector(".t-tag");
    const description = row.querySelector(".t-description");
    const image = row.querySelector(".t-img");

    title.textContent = cocktail.strDrink;
    tag.textContent = cocktail.strTags ?? "Generic";
    description.textContent = cocktail.strInstructions;
    image.src = cocktail.strDrinkThumb;

    list.appendChild(row);
  });
}

/**
 * Realiza la petición de datos a la api.
 */
async function fetchCocktails(search = "a") {
  const response = await fetch(`${API_SEARCH}?s=${search}`, {
    method: "GET"
  })
    .then(function (response) {
      return response.json();
    })
    .catch(function (error) {
      console.log("Error en la petición AJAX:", error);

      return null;
    });

  // Almaceno en la variable global todos
  cocktails = response && response.drinks ? response.drinks : null;

  // Actualizo la lista con los cócteles
  updateCocktailsList();

  console.log("FIN consulta Fetch:", cocktails);
}

// Acciones que se realizarán una vez esté cargada la página por completo.
window.document.addEventListener("DOMContentLoaded", () => {
  // Obtiene por primera al cargar la página.
  fetchCocktails();

  // Añado eventos al buscador.
  let sarchInput = document.getElementById("input-search");
  sarchInput.addEventListener("change", handleOnChangeInputUpdate);
  sarchInput.addEventListener("keyup", handleOnChangeInputUpdate);
});

              
            
!
999px

Console