Trigger an Event When User Reaches the Bottom of the Page

In a previous project, a client requested an action to be performed when the user scrolled to the bottom of the page or reached the last element in a list. Here’s how I implemented this functionality using vanilla JavaScript.

Detecting When the User Reaches the Bottom of the Page

To trigger an event when the user scrolls to the bottom of the page, we can compare the sum of the window’s inner height and the current scroll position with the document’s total scroll height. If they are equal, the user has reached the bottom.

window.addEventListener('scroll', function() {
  // Check if the user has scrolled to the bottom of the page
  if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {
    // Perform the desired action, e.g., showing a popup
    document.getElementById('popup').style.display = 'block';
  }
});

Detecting When the User Reaches the Last List Item

If you want to trigger an event when the user scrolls to the last list item in a <ul> or <ol>, you can check if the last list item is visible in the viewport.

window.addEventListener('scroll', function() {
  // Get the last list item
  const lastItem = document.querySelector('#list li:last-of-type');

  // Check if the last list item is visible
  if (lastItem && isElementInViewport(lastItem)) {
    // Perform the desired action, e.g., showing a popup
    document.getElementById('popup').style.display = 'block';
  }
});

// Helper function to determine if an element is in the viewport
function isElementInViewport(el) {
  const rect = el.getBoundingClientRect();
  return rect.top >= 0 && rect.left >= 0 &&
         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
         rect.right <= (window.innerWidth || document.documentElement.clientWidth);
}

Scroll Event Listener: We add an event listener to the scroll event on the window object. This ensures that our function is called every time the user scrolls.

Checking Scroll Position: We compare the sum of window.innerHeight (the height of the viewport) and window.scrollY (the number of pixels the document is currently scrolled vertically) with document.body.scrollHeight (the total height of the document). If they are equal, the user has reached the bottom of the page.

Checking Element Visibility: To determine if the last list item is visible, we use the getBoundingClientRect() method to get the position of the element relative to the viewport. We then check if the element’s top and bottom are within the visible area of the viewport.

You can customize the actions performed when the user reaches the bottom of the page or the last list item. For example, instead of showing a popup, you might want to load more content dynamically, display a “Back to Top” button, or trigger an animation.

on in JavaScript DOM | Last modified on

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *