Identifying the completion of scrolling within a container

I'm facing a challenge with my dynamic website that has numerous blog posts. My goal is to initially load only four posts and then add another four as the user scrolls to the end of the page. While I have figured out how to handle this on the backend, I am encountering issues on the frontend. Setting the height of html and body to 100% prevents scroll events on the window from working properly. To work around this, I decided to use a single div element to detect scrolling. Adding a scroll event listener to the div worked well, but I ran into trouble when trying to determine if the end of the scroll had been reached. The code I used was:

if (element.scrollHeight - element.scrollTop === element.clientHeight){
   alert("End");
}

How can I ensure that the alert only appears once the div has been scrolled to the end, rather than at the beginning of the page load?

Answer №1

To detect the end of a scroll, you can utilize the following code:

element.scrollTop + element.offsetHeight>= element.scrollHeight
.

Update: Additionally, you can include a condition to prevent firing when scrolling upwards. For more information on detecting upward scroll conditions, refer to this link.

const element = document.getElementById('element');
let lastScrollTop = 0;
element.onscroll = (e)=>{
if (element.scrollTop < lastScrollTop){
      // upscroll 
      return;
   } 
   lastScrollTop = element.scrollTop <= 0 ? 0 : element.scrollTop;
    if (element.scrollTop + element.offsetHeight>= element.scrollHeight ){
       console.log("End");
    }
}
#element{
  background:red;
  max-height:300px;
  overflow:scroll;
}
.item{
height:100px;
}
<div id="element">
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div>

Answer №2

Solution for the upcoming year 2023.
Exciting news! We now introduce the new scrollend event.
Successfully tested on chromium 108 and firefox 109 browsers.

Check out this example:

const result = document.querySelector("p#result");

document.addEventListener("scrollend", (event) => {
  result.innerHTML = `The Document scrollend event has been triggered!`;
});

Based on information from mdn documentation:
The scrollend event is activated once the document finish its scrolling process.
Scrolling is considered finished when there are no pending updates to the scroll position and
the user has completed their interaction.

Learn more about it on mdn: Document: scrollend event

Answer №3

if (element.scrollTop + element.offsetHeight >= element.scrollTopMax) {
    // This is the condition I often rely on
}

This code snippet serves as a crucial checkpoint for my application.

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

Issues with jQuery dataTable causing JavaScript type "GET" to not reach the controller

Something peculiar is happening! I can successfully reach the controller by making a direct ajax call, but when trying to do the same from inside the dataTable code block, it seems like the execution never reaches the controller. Although I'm new to ...

Embed the json data within the modal box

I received a JSON response from a php function, and it looks like this: [{"id":"15","activity_type":"call","activity_title":"Call to check "}] Below is the script that triggers the request (actvitiy.js) (Edited) $(document).on("click", ".view_contact_ac ...

Guide to utilizing variables with Pattern.compile in Java for selenium RC

I am facing a challenge where I need to check if the date in a field corresponds to the current day. In Selenium IDE, this is easily achieved: <tr> <td>storeExpression</td> <td>javascript{var date = new Date ...

What is the method for designing a relative layout that organizes elements horizontally?

Can you tell me why elements are typically arranged vertically in a column? Is it feasible to change their orientation and display them horizontally, like in a row instead of a column? ...

When attempting to implement sound on hover with an <a attribute containing an image>, the functionality is not functioning as expected

Is there a way to make a sound play only once when hovering over a list item that contains an image? Here is the HTML and JavaScript code I am using: function playclip() { var audio = document.getElementsByTagName("audio")[0]; audio.play(); } <ul ...

Retrieve the values of the recently selected options in a multiple selection

I am trying to retrieve the last or most recently selected option value from a dropdown menu. In my Django code, I have attempted the following: <script type="text/javascript> django.jQuery(document).ready(function(){ django ...

Which method is more effective: utilizing AJAX to retrieve page elements, or just toggling their visibility?

When it comes to web development, particularly in jQuery, should I preload my page and use jQuery to manipulate the DOM, or should I do it the other way around? This debate involves: <div id="item1" ></div> <div id="item2"></div> ...

Sequence of loading unique CSS skin for MediaWiki

Running a MediaWiki site with a personalized skin, I've noticed that the CSS code from my custom skin is being overshadowed by the default MediaWiki CSS. Is there a way to modify the sequence in which the CSS code is loaded? ...

Retrieve the initial identification number from a sorted list using Jquery UI Sortable

Situation: My task involves developing a mobile website that allows users to organize a list of names using the Jquery UI sortable option. Depending on the order in which the names are arranged, additional information will be displayed on the next page. ...

Trouble with uploading images to folder using PHP and AJAX is causing confusion

I'm having trouble uploading a photo using ajax and php. Despite following advice from other sources, I can't seem to make it work. Is there anything in my code that appears to be incorrect? The ajax request seems to go through successfully, so ...

ES6: Using DataURI to provide input results in undefined output

In my current project, I am facing a challenge. I am attempting to pass image dataURI as an input from a url link to the image. To achieve this task, I know that I have to utilize canvas and convert it from there. However, since this process involves an &a ...

Maintain the values of radio buttons, dropdowns, and checkboxes using Javascript

When I click on a radio button, it activates a drop down menu. Upon selecting different values from the drop down, various checkboxes become visible. Now, I want to preserve the selection of the radio button along with the selected drop down values and ch ...

What is the method for setting a default value for a disabled input?

<input type="checkbox" disabled="disabled" checked="checked" name="is_ok" id="id_is_ok"/> Is there a way to set a default value for this disabled input? I've noticed that if this field is disabled and I make edits to my data, the changes are n ...

Place text in the center of a div and add a numbered circle beside it

I need help adding a circle with a number next to a div containing centered text. Take a look at the image I have attached for reference. https://i.sstatic.net/tHA65.png I believe I am close to achieving the desired outcome, but I am struggling to center ...

Manage an error request with unique parameters

I recently made a GET request using axios in my web application: axios({ method: 'get', url: "example.com", params:{ _id: "anId" } }) .th ...

Why isn't the pipe working when trying to extract the last 2 characters using

I am currently working on creating a regex pattern to extract the variables passed to a JavaScript constructor. The format of the input data will always be similar to this: app.use(express.static('public')); The regex I have devised to remove ...

Preventing the copying and pasting of HTML ruby tags

I am currently using ruby tags to include pinyin in my text. For instance: <p> <ruby>与<rt>yǔ</rt></ruby><ruby>摩<rt>mó</rt></ruby><ruby>拜<rt>bài</rt></ruby><ruby& ...

Steps to load a script when the document is ready:

What is the best method to include JavaScript using the following code: <script type="text/javascript" src="http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869"></script> only after the page has fully loaded? $(document).ready(funct ...

Exploring ways to retrieve items from a JSON array in Node.js, ideally avoiding traditional iteration methods

In my current scenario, the JSON response I receive looks like this... {items:[ {itemId:1,isRight:0}, {itemId:2,isRight:1}, {itemId:3,isRight:0} ]} My goal is to achieve something similar to the following (pseudo code) var arrayFound = obj.items.F ...

Converting objects to arrays in reactJS

Here is the object structure I currently have: { DepositAmt_0: 133 DepositAmt_1: 455 DepositAmt_2: 123 DepositNotes_0: "some notes " DepositNotes_1: "some comment" DepositNotes_2: "some comme ...