Road to infinity

02. January 2019

Intro­duc­tion

In this post I show how to use Ajax jQuery Scripts to imple­ment an infi­nite scroll through your blog arti­cles.

Instal­la­tion

Down­load the requi­red Java­script File jquery-ias.min.js from Infi­nite Ajax Scroll and put it into assets/vendor/infinite/.

Edit your tem­pla­tes

Wrap your cur­rent arti­cle loop into a div (e.g. blog.php, if you are using the example from the kirby site) or use an exis­ting 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 iden­ti­fia­ble class (here right in pagination.php), if not alre­ady done:

<?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 snip­pets

Include the requi­red Java­Script in your header.php (or com­bine them with your exis­ting js): 

<?= js('assets/vendor/infinite/js/jquery-ias.min.js') ?>

Activate the Ajax by also inclu­ding this script (infinite.js) (adjust the iden­ti­fier 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 some­thing dif­fe­rent by adjus­ting the para­me­ter to IASSpinnerExtension():

// Add a loader image which is displayed during loading
ias.extension(new IASSpinnerExtension({
    src: '/assets/images/loader.svg',
}));    

This could be even an svg image like this: