Skip to content
Advertisement

How can run a function when content of an element is loaded. Loading more items from a server

I am loading and appending more items from a server to a div. And when they are fully loaded I want to run a function that will refresh colcade layout (reloadColcade).

I have tried adding an event listener to the div with options like ‘load’ and ‘DOMContentLoaded’, divElement.addEventListner('option', reloadColcade) but the event isn’t fired.

And when I try to setTimeout to wait for elements to load either function is invoked too early or too late.

<div class="articles-container grid" data-articles-grid="">
          <div class="grid-col grid-col--1"></div>
          <div class="grid-col grid-col--2"></div>
          <div class="grid-col grid-col--3"></div>

          <% products.forEach(product => { %>
            <% const date = product.createdAt.toISOString().split('T')[0].replaceAll('-', '/'); %> 

            <article class="ver-spacer grid-item" id="<% product._id %>">
              <img src="<%= product.optimizedImgUrl %>" data-original-img-source="<%= product.imgUrl %> " alt="article photo" class="articles-container__article-img">
              <h2><%= product.title %></h2>
              <p><%= product.description %> <button class="articles-container__highlight">Read more</button></p>
              <div class="articles-container__article-info separetor"><p>Price: <%= product.price  %> &#36</p><p>Author: <%= product.authorName %> </p><p>Uploaded: <%= date %></p> <p>Resolution: <%= product.resolution %></p></div>
              <button class="btn-gray articles-container__button ai-c">Add <img src="img/shopping-cart.svg" alt="shopping cart"></button>
          </article>
          <% }); %>
</div>

let colc, colcUploadedByUser, colcPurchasedByUser;
let searchQuery, filter;

const loadMore = async function () {
  let startIndex = 0;

  startIndex += 5;

  const searchQuery = searchForm.querySelector("input").value;
  const filter = searchForm.querySelector("select").value;

  const response = await fetch("load-more", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      startIndex,
      searchQuery,
      filter,
    }),
  });

  const products = await response.json();

  let itemsToAppend = [];

  products.forEach((product) => {
    const date = new Date(product.createdAt)
      .toISOString()
      .split("T")[0]
      .replaceAll("-", "/");

    const htmlString = `
      <img src="${product.optimizedImgUrl}" data-original-img-source="${product.imgUrl}" alt="article photo" class="articles-container__article-img">
      <h2>${product.title}</h2>
      <p>${product.description} <button class="articles-container__highlight">Read more</button></p>
      <div class="articles-container__article-info separetor"><p>Price: ${product.price} &#36</p><p>Author: ${product.authorName} </p><p>Uploaded: ${date}</p> <p>Resolution: ${product.resolution}</p></div>
      <button class="btn-gray articles-container__button ai-c">Add <img src="img/shopping-cart.svg" alt="shopping cart"></button>
      `;

    const item = document.createElement("article");

    item.className = "ver-spacer grid-item";
    item.setAttribute("id", product._id);
    item.insertAdjacentHTML("beforeend", htmlString);

    itemsToAppend.push(item);
  });

  colc.append(itemsToAppend);
};

// Colcade
if (document.querySelector(".grid")) {
  colc = new Colcade(".grid", {
    columns: ".grid-col",
    items: ".grid-item",
  });
}

const reloadColcade = function () {
  colc && colc.layout();
  colcUploadedByUser && colcUploadedByUser.layout();
  colcPurchasedByUser && colcPurchasedByUser.layout();
};

Advertisement

Answer

I solved the problem by using library imagesloaded also created by author of colcade, like that:

import * as imagesloaded from "./node_modules/imagesloaded/imagesloaded.pkgd.min.js";

imagesLoaded(colc.element, function () {
    reloadColcade();
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement