skip to Main Content

Can u guys help me how to create load more with my javascript

and this is my javascript for fetch API resource

<script type="text/javascript">
  const filterProduct = document.getElementById("filterProducts");
  const domain = window.location.host
  if (filterProduct) {
    // Fetch JSON data and generate HTML
    fetch(`http://api.${domain}/v2/categories`)
      .then((response) => response.json())
      .then((data) => {
        const generateCTGameHTML = (games, targetElementId) => {
          const gameListHTML = games
            .map(
              (game) => `
                <a class="group relative transform overflow-hidden rounded-2xl bg-murky-700 duration-300 ease-in-out hover:shadow-2xl hover:ring-2 hover:ring-primary-500 hover:ring-offset-2 hover:ring-offset-murky-900" href="order/${game?.slug}" style="outline: none;">
                  <img alt="${game?.title}" width="192" height="288" class="aspect-[4/6] object-cover object-center" src="${game?.image}" style="color: transparent;">
                  <article class="absolute inset-x-0 -bottom-10 z-10 flex transform flex-col px-3 transition-all duration-300 ease-in-out group-hover:bottom-3 sm:px-4 group-hover:sm:bottom-4">
                    <h2 class="truncate text-sm font-semibold text-murky-200 sm:text-base">${game?.title}</h2>
                    <p class="truncate text-xxs text-murky-400 sm:text-xs">${game?.production}</p>
                  </article>
                  <div class="absolute inset-0 transform bg-gradient-to-t from-transparent transition-all duration-300 group-hover:from-murky-900"></div>
                </a>
              `
            )
            .join("");

          const gameListElement = document.getElementById(targetElementId);
          gameListElement.innerHTML = gameListHTML;
        };
        data.forEach(function(cat){
            generateCTGameHTML(cat.lists, cat.panel);
        });
      })
      .catch((error) => console.log("Error:", error));
  }
    // Drawer Menu
    function drawerMenu() {
      return {
          open: false,
          usedKeyboard: false,
          init() {
              this.$watch('open', value => {
                  value && this.$refs.closeButton.focus()
                  this.toggleOverlay()
              })
              this.toggleOverlay()
          },
          toggleOverlay() {
              document.body.classList[this.open ? 'add' : 'remove']('h-screen', 'overflow-hidden')
          }
      }
  }

</script>

this my html

 <div id="filterProducts">
            @foreach ($typecategories as $item)
                <div class="hidden" id="{{ preg_replace('/s+/', '', $item->name) }}panel" role="tabpanel" aria-labelledby="{{ preg_replace('/s+/', '', $item->name) }}panel-tab">
                <div id="{{ preg_replace('/s+/', '', $item->name) }}" class="grid grid-cols-3 gap-4 sm:grid-cols-4 sm:gap-x-6 sm:gap-y-8 lg:grid-cols-5 xl:grid-cols-6"></div>
                </div>
            @endforeach
          </div>

in my html code not add a button from load more because i dont know how to called in javascript system,
and i need load more form diferent panels like my json

2

Answers


  1. Chosen as BEST ANSWER

    This my json form API

    [
        {
            "_id": "B0AACBFC143915E51DA0",
            "panel": "TopUps",
            "lists": [
                {
                    "_id": "4D9D082AA579BC083B91",
                    "title": "Mobile Legend",
                    "production": "Moonton",
                    "slug": "mobile-legend",
                    "image": "http://api.bjtopupku.test/storage/categories/B2C0EEDC2F7F3F3FED99.webp"
                },
                {
                    "_id": "9DBEA3A115CFCBF0588F",
                    "title": "Call Of Dutty",
                    "production": "Garena",
                    "slug": "call-of-dutty",
                    "image": "http://api.bjtopupku.test/storage/categories/DAD584AD18173A577DB8.webp"
                },
                {
                    "_id": "262C4C5EE1E3155FD336",
                    "title": "Free Fire",
                    "production": "Garena",
                    "slug": "free-fire",
                    "image": "http://api.bjtopupku.test/storage/categories/2EA149D36A8F45505FD1.webp"
                }
            ]
        },
        {
            "_id": "352426BF7F7B9A697148",
            "panel": "Voucher",
            "lists": [
                {
                    "_id": "9AAB33BCF8405239AAC9",
                    "title": "TESTING KATEGORI",
                    "production": "TESTING",
                    "slug": "testing-kategori",
                    "image": "http://api.bjtopupku.test/storage/categories/729B1BF05BC9F54A2696.webp"
                },
                {
                    "_id": "AFCF4BCE0B7FE85B3578",
                    "title": "asdsda",
                    "production": "asdasdasd",
                    "slug": "asdsda",
                    "image": "http://api.bjtopupku.test/storage/categories/642AF002249DEDF5DD91.webp"
                },
                {
                    "_id": "DD890C5739C94F809296",
                    "title": "asddassda",
                    "production": "sdaasdsda",
                    "slug": "asddassda",
                    "image": "http://api.bjtopupku.test/storage/categories/C7F9F5CBD230FB7D27F2.webp"
                }
            ]
        }
    ]


  2. Modify your HTML to include a "Load More" button for each panel

    <div id="filterProducts">
        @foreach ($typecategories as $item)
            <div class="hidden" id="{{ preg_replace('/s+/', '', $item->name) }}panel" role="tabpanel" aria-labelledby="{{ preg_replace('/s+/', '', $item->name) }}panel-tab">
                <div id="{{ preg_replace('/s+/', '', $item->name) }}" class="grid grid-cols-3 gap-4 sm:grid-cols-4 sm:gap-x-6 sm:gap-y-8 lg:grid-cols-5 xl:grid-cols-6"></div>
                <button class="load-more-button" data-panel-id="{{ preg_replace('/s+/', '', $item->name) }}">Load More</button>
            </div>
        @endforeach
    </div>
    

    Next, modify your JavaScript to handle the "Load More" button click event and fetch additional data:

    const filterProduct = document.getElementById("filterProducts");
    const domain = window.location.host;
    
    if (filterProduct) {
        const fetchGames = async (panelId) => {
            const response = await fetch(`http://api.${domain}/v2/categories/${panelId}`);
            const data = await response.json();
            return data.lists;
        };
    
        const generateCTGameHTML = (games, targetElementId) => {
            const gameListHTML = games
                .map(
                    (game) => `
                        <a class="group relative transform overflow-hidden rounded-2xl bg-murky-700 duration-300 ease-in-out hover:shadow-2xl hover:ring-2 hover:ring-primary-500 hover:ring-offset-2 hover:ring-offset-murky-900" href="order/${game?.slug}" style="outline: none;">
                            <img alt="${game?.title}" width="192" height="288" class="aspect-[4/6] object-cover object-center" src="${game?.image}" style="color: transparent;">
                            <article class="absolute inset-x-0 -bottom-10 z-10 flex transform flex-col px-3 transition-all duration-300 ease-in-out group-hover:bottom-3 sm:px-4 group-hover:sm:bottom-4">
                                <h2 class="truncate text-sm font-semibold text-murky-200 sm:text-base">${game?.title}</h2>
                                <p class="truncate text-xxs text-murky-400 sm:text-xs">${game?.production}</p>
                            </article>
                            <div class="absolute inset-0 transform bg-gradient-to-t from-transparent transition-all duration-300 group-hover:from-murky-900"></div>
                        </a>
                    `
                )
                .join("");
    
            const gameListElement = document.getElementById(targetElementId);
            gameListElement.insertAdjacentHTML('beforeend', gameListHTML);
        };
    
        filterProduct.addEventListener('click', async (event) => {
            if (event.target.classList.contains('load-more-button')) {
                const panelId = event.target.dataset.panelId;
                const games = await fetchGames(panelId);
                generateCTGameHTML(games, panelId);
            }
        });
    
        // Initial loading of games
        document.querySelectorAll('.load-more-button').forEach(async (button) => {
            const panelId = button.dataset.panelId;
            const games = await fetchGames(panelId);
            generateCTGameHTML(games, panelId);
        });
    }
    

    Let me know if that helps. Thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search