Infinite Scroll

Overview

This sample initially loads five articles on the page. As users scroll down, additional articles are automatically loaded when they reach the bottom.

Client Content

Below is the Lava template for the front-end client. While we could load the initial items in this template, it is simpler and more consistent to handle this at the back-end endpoint.

<div class="articles">
    <div class="article" hx-get="^/helix-gallery/articles-infinitescroll?page=0" hx-trigger="load" hx-swap="outerHTML">
    </div>
</div>

Endpoint Template

Here is the Lava template for the endpoint.

{% assign pageNumber = QueryString.page%}
{% assign nextPageNumber = pageNumber | Plus:1%}

{% assign itemsPerPage = 5%}
{% assign offsetAmount = pageNumber | Times:itemsPerPage%}

{% contentchannelitem where:'ContentChannelId == {{ ConfigurationRigging.ArticleContentChannelId }}' sort:'StartDateTime desc' limit:'{{ itemsPerPage }}' offset:'{{ offsetAmount }}' securityenabled:'false'%}

    {% for item in contentchannelitemItems%}
    
        
        {% assign returnCount = contentchannelitemItems | Size%}
        {% if forloop.last and returnCount == itemsPerPage%}
            {% capture nextPageCall%}hx-get="^/helix-gallery/articles-infinitescroll?page={{ nextPageNumber}}" hx-trigger="revealed" hx-swap="afterend" {% endcapture%}
        {% endif%}
        
        <div class="article card mb-3 d-flex flex-row" {{ nextPageCall}}>
            <img class="card-image width-third" src="{{ item | Attribute:'Image','RawValue'}}">
            <div class="card-content align-self-center ml-3">
                <h4>{{ item.Title}}</h4>
                <p><small class="text-muted">{{ item | Attribute:'Author'}}</small></p> 
                <p>{{ item | Attribute:'Summary'}}</p>
            </div>
        </div>
    
    {% endfor%}

{% endcontentchannelitem%}
Trip Hazard Note that on line 17 of the endpoint the final article div will set the hx-swap to 'afterend'. This property is inherited down the DOM. If you have any other HTMX commands inside of the article their swap will also be 'afterend' which might not be what you intend. In these cases you'll want to redefine the hx-swap back to something like 'innerHTML'.

Demo

Here's the working demo of this feature, currently paging five items at a time. For most use cases, you may want to load more items simultaneously.