Note

Hey! 
Since this blogpost was written, I created a new and improved way to do infinite scrolling. Check out this YouTube Video to see the latest implementation. 

Legacy Implementation

Htmx superpowers your html, allowing it to do things you would typically have to do in JavaScript. After discovering issues with duplicate pages due to my pagination implementation, I removed all the duplication with infinite scroll!

Luckily, I came across an excellent youtube video by bugBytes who walks you through how to pull off infinite scroll with htmx.

I won't bore you with all the details, but I will highlight how I adjusted the implementation to handle category pages.

In bugByte's example, he hardcodes the URL to fetch articles since he is only working with one view:

<div hx-get="{% film-list %}?page={{ page_obj.number|add:1 }}" hx-trigger="revealed" hx-swap="afterend" hx-target="this">

In my case, posts can come from multiple views. I modified the request to reference a url variable I passed within the view to support more than one view. Notice I replace film-list with url.

<div hx-get="{{ url }}?page={{ page_obj.number|add:1 }}" hx-trigger="revealed" hx-swap="afterend" hx-target="this">

Within each view, I pass the current path into the template as a context variable:

class CategoryView(ListView):
	...
    def get_context_data(self, *args, **kwargs):
        ...
        context["url"] = self.request.path
        return context

This way, the template is always fetching the correct url!

Conclusion

After running into issues with duplicate content with my previous pagination implementation, I decided to use htmx to implement infinite scrolling. This resolved the duplication issue and introduced new functionality. I call that a win!

See the PR where I implemented infinite scroll.

Comments

  • freedompraise July 24, 2023
    Woaw.
    I have faced issues with infinix scrolling while using HTMX.
    I'm going to try this out!
  • Login to Comment
Back to Home
John Solly Profile Picture
John Solly Profile Picture

John Solly

Hi, I'm John, a Software Engineer with a decade of experience building, deploying, and maintaining cloud-native geospatial solutions. I currently serve as a senior software engineer at HazardHub (A Guidewire Offering), where I work on a variety of infrastructure and application development projects.

Throughout my career, I've built applications on platforms like Esri and Mapbox while also leveraging open-source GIS technologies such as OpenLayers, GeoServer, and GDAL. This blog is where I share useful articles with the GeoDev community. Check out my portfolio to see my latest work!