Has anyone implemented infinite scrolling on a Hugo website?

I found that the infinite-scroll package by Mettafizzy is perfect for this use-case. It works off of paginated content to create an infinite scroll. If JavaScript is disabled the user would just continue to use the paginated content.

The library is free to use in open source projects. There is a license fee for commercial projects. See more detail on licensing.

In my case I have 7 stories per page to avoid loading lots of large images. The markup is like so:

Blog content markup

<ul class="card-list">
  <li class="card">
    <!-- Content goes here -->
  </li>
  <li class="card">
    <!-- Content goes here -->
  </li>
  <li class="card">
    <!-- Content goes here -->
  </li>
  <li class="card">
    <!-- Content goes here -->
  </li>
</ul>

<!-- Pagination goes here -->

Customized pagination

I added a pagination-next class to the next button so the infinite scroll JS could find the next page of content, which it will load and append to my list. The library automatically increments page numbers to add the appropriate content as the user scrolls. It even updates the URL and relies on the history API to enable back/forward buttons on the browser.

<li {{ if not $pag.HasNext }}class="disabled"{{ end }}>
  <a href="{{ if $pag.HasNext }}{{ $pag.Next.URL }}{{ end }}" aria-label="Next" class="pagination-next">
    <span aria-hidden="true">&raquo;</span>
  </a>
</li>

JavaScript

The beauty of this approach is the simplicity of the infinite scroll library. It just requires a little bit of info about how your pagination is set up, then takes care of the rest.

const InfiniteScroll = require('infinite-scroll'); // installed via NPM

const elm = document.querySelector('.card-list');

const options = {
  path: '.pagination-next',
  append: '.card'
};

const infScroll = new InfiniteScroll(elm, options);

Result

5 Likes