When you reach the halfway point of the page, the infinite scroll feature will be activated

I have a situation where I need to load more products from an API when the user scrolls to the middle of the page. I have successfully implemented the code for this feature, but I am facing two issues. Firstly, the function gets called multiple times when I scroll to the end of the products, which is the expected behavior. How can I ensure that the function is called only ONCE when reaching the end of the products? Secondly, I need to determine the direction of the scroll event - specifically, I want to trigger the API request only when the user scrolls from top to bottom and reaches the end of the products.

window.addEventListener('scroll', () => {
  if(this.isInViewport){
      //api request
      }
  })

isInViewport(){
  const bounding = this.$refs.button.getBoundingClientRect();
      return (
         bounding.top >= 0 &&
         bounding.left >= 0 &&
         bounding.bottom <= (window.innerHeight || 
         document.documentElement.clientHeight) &&
         bounding.right <= (window.innerWidth || 
         document.documentElement.clientWidth));
}

My expectation is to make the API request just once per end of the products

Answer №1

If you're looking to enhance user experience, check out the powerful Intersection Observer API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

While it can be a game-changer, keep in mind that it may not be fully supported by all browsers.

Regardless, you can adjust your code like this for a more efficient implementation:

let requestSent = false

window.addEventListener('scroll', () => {
  if(this.isInViewport && !requestSent){
      requestSent = true;

      //make the API request
      ApiRequest().then(() => requestSent = false);
      }
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transfer data from an AJAX GET request to a Node.js GET route?

Here is an example of an ajax request being made $.ajax({ url: '/reload', type: 'GET', contentType: "application/json", data: { Name: $("#inputName").val(), Link: $("#inputLink").val() }, succe ...

Using Vue.js for displaying strings with line breaks

I'm struggling to include a line break in string interpolation within my printed HTML this.externalUsers = data.externalUser.map(element => `Name: ${element.firstName} ${element.lastName}\n <br><br />Email: ${element.email}`); In ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

How can I extract a distinct integer value from a MongoDB ObjectId using JavaScript in NodeJS?

In my current project, we are utilizing MongoDB as our primary database system alongside JavaScript/NodeJS for the server-side operations. We now face the challenge of integrating with an external partner. Our partner's API necessitates a unique inte ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

Leverage the Power of JSON Data Manipulation in WordPress with Angular JS and the WordPress JSON

After testing code in this particular post and making some adjustments, I encountered an issue with obtaining a JSON object from the API of my blog created using the WordPress JSON plugin. URL of API from BLOG (NOT FUNCTIONING): URL from W3C example (WO ...

Is there a way to determine if an array contains multiple occurrences of unidentified strings?

Is there a way in JavaScript to determine if an array contains two or more identical values? For instance; ['one','two','three'] -> false, because no items in the array are repeated. ['one','one',&apo ...

What is the most efficient way to apply a single click handler instead of using multiple click handlers for the same

Check out the project I'm currently working on by following this link: The link provided above contains a list of clickable colors available on the right side. When a user clicks on a color, the images on the left side change accordingly. Below is t ...

Strip away styles and scripts from PartialView

Looking to incorporate a Star Rating system using a PartialView named: @{ Html.RenderAction("Rate"); } The goal is to display and manage the star rating code separately from the current page, eliminating the need for the parent .cshtml's CSS and oth ...

No default export function available on this page

Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration. Let me showcase my code: import type { NextApiRequest, NextApiResponse } from 'next' import { connectMongoDB } fro ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Audio waves visualization - silence is golden

I am attempting to create a volume meter, using the web audio API to create a pulsation effect with a sound file loaded in an <audio> element. The indicator effect is working well with this code; I am able to track volume changes from the playing aud ...

AngularJS simplifies request handling by allowing currying of requests

I am working with three forms within the same container, each triggered by a specific objectId. I want to create a function that can handle all actions related to these objectIds. Unfortunately, I am restricted to using ES5. var applyActions = function( ...

Tips for displaying data from an Axios call using the map method

I'm encountering an issue while attempting to showcase the outputs retrieved from an axios operation in React. Although I have already set up the mapping within the function, I can only view the outcomes defined in the initial 'then' through ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

Evaluate JavaScript code on the client side that modifies the DOM without using a browser through programming

Is it feasible to achieve something similar to this scenario: Send a request to the website I am trying to scrape. The website utilizes client-side and potentially server-side JavaScript to make requests and modify the Document Object Model (DOM). For e ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...

The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit and I have a controller that combines both the view and edit functionalities: ... if ($routeParams.id) { $scope.itemId = $routeParams.id; $scope.editMode = true; Item.getB ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...