FacetWP: Spinning While Updating

When you use FacetWP you can do some cool things like change the ‘count’ output of a page. Using the function facetwp_display() you can add facetwp_display( 'counts' ) to your page title, and then a boring old archive title goes from “List of Characters (2022)” to “List of Characters (1-24 of 2022)”

But… What if you could do more?

What Could Be More?

If you have a lot of data, sometimes a page can load and FacetWP spins while it collects everything in it’s wee javascripty brain. When that happens, you have a cognitive moment of “What?” And in order not to lose a user, you want to indicate, somehow, that an action is happening. A spinning icon is, I think, a great way to do that.

So with that in mind, I want to do this:

List of Characters showing a spinning icon for the number

And I did.

The Code

This needs javascript. I used some logic from the FacetWP documentation and some memories about how you can replace text with javascript and came up with this:

(function($) {
	$(document).on('facetwp-refresh', function() {
		$('.facetwp-count').html('<i class="fa fa-spinner fa-pulse fa-fw"></i><span class="sr-only">Loading...</span>');
	});
    
    $(document).on('facetwp-loaded', function() {
	   $('.facetwp-count').html('');
	});
    
})(jQuery);

Then I slap it into my PHP code like so:

$count_posts = facetwp_display( 'counts' );

the_archive_title( '<h1 class="facetwp-page-title page-title">' . $title, ' (' . $count_posts . '<span class="facetwp-count"></span>)</h1>' );

The content for $count_posts shows nothing while it’s loading, so the check for facetwp-loaded will handle it perfectly.