Time for a little giveback to the community…and because I’ve already written it for my blog, I thought it would be a good idea to post it here…
Introduction
In this post I show how to use Ajax jQuery Scripts to implement an infinite scroll through your blog articles.
Installation
Download the required Javascript File jquery-ias.min.js
from (link: https://infiniteajaxscroll.com text: Infinite Ajax Scroll) and put it into assets/vendor/infinite/
. Include jquery in your header.php if you not already have.
Edit your templates
Wrap your current article loop into a div (e.g. blog.php
, if you are using the example from the kirby site) or use an existing class:
<div id="blog">
<section class="wrap">
<?php if($articles->count()): ?>
<?php foreach($articles as $article): ?>
<article class="blog-article index">
...
</div>
Give your Next Link an identifiable class (here: right
in pagination.php
):
<?php if ($pagination->hasPages()) : ?>
<nav class="pagination wrap cf">
...
<?php if($pagination->hasNextPage()): ?>
<a class="pagination-item right" href="<?= $pagination->nextPageURL() ?>" rel="next" title="older articles">
<?= (new Asset("assets/images/arrow-right.svg"))->content() ?>
</a>
...
Update your snippets
Include the required JavaScript in your header.php
(or combine them with your existing js):
<?= js('assets/vendor/infinite/js/jquery-ias.min.js') ?>
Activate the Ajax by also including this script (infinite.js
) (adjust the identifier to match your class names):
var ias = jQuery.ias({
container: '#blog',
item: '.blog-article',
pagination: '#pagination',
next: '.right'
});
// Add a loader image which is displayed during loading
ias.extension(new IASSpinnerExtension());
// Add a link after page 2 which has to be clicked to load the next page
ias.extension(new IASTriggerExtension({offset: 2}));
// Add a text when there are no more pages left to load
ias.extension(new IASNoneLeftExtension({text: "You reached the end"}));
Finally you can change the loader images to something different by adjusting the parameter to IASSpinnerExtension()
:
// Add a loader image which is displayed during loading
ias.extension(new IASSpinnerExtension({
src: '/assets/images/loader.svg',
}));
You can see it in action on my blog.