Intersection Observer API

The Intersection Observer API allows you to detect when an element enters or leaves the viewport. This is exceptionally useful for implementing infinite scroll.

<style>
 #load-more-trigger {
    height: 1px;
    width: 100%;
 }
</style>

<div id="content-container">
    <!-- Existing content items here -->
</div>
<div id="load-more-trigger"></div>


$(document).ready(function() {
    let loading = false; // Prevents multiple requests at once
    let observerOptions = {
        root: null, // Use the viewport as the root
        rootMargin: '0px', // No margin around the root
        threshold: 0.1 // Trigger when 10% of the target is visible
    };


    let observer = new IntersectionObserver(function(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting && !loading) {
                loading = true;
                loadMoreContent(); // Load more content when the trigger is in view
            }
        });
    }, observerOptions);


    // Start observing the trigger element
    observer.observe(document.querySelector('#load-more-trigger'));


    function loadMoreContent() {
        // Simulate an AJAX request to load more content
        $.ajax({
            url: 'path/to/your/api', // Replace with your content API or server endpoint
            method: 'GET',
            success: function(data) {
                // Append new content to the container
                $('#content-container').append(data);


                // Reset the loading flag
                loading = false;
            },
            error: function() {
                console.log('Error loading more content');
                loading = false;
            }
        });
    }
});