Dynamic Blog Navigation | Prev/Next Buttons?

Hi,
I think this might work out to be a smooth fix until sitejet provides navigation. Basically You create the buttons in the single page layout and this script will update the href of your buttons or disable them as appropriate.

Note the button IDs, also note your collectionId for the API call and your slug for the collection then update the script. Then paste the script after the HTML {{content}} in the code editor.

<script>
document.addEventListener('DOMContentLoaded', () => {
// UPDATE THESE VALUES
  const collectionId = '<your id>';
  const collectionSlug = '<your collection slug>' ;
  const prevBtnId = '<previous button id>';
  const nextBtnId = '<next button id>';
  
  const api = `https://api.sitehub.io/collection/${collectionId}/items?order=createdAt_ASC`;

  fetch(api)
    .then(r => r.json())
    .then(({ collection }) => {
	
	  if (!Array.isArray(collection) || !collection.length) return; // nothing returned – abort
	  
	  const slugs = collection.map(item => item.columns?.slug).filter(Boolean);  
      const current = window.location.pathname.split('/').filter(Boolean).pop();
      const idx = slugs.indexOf(current);
      if (idx === -1) {
	    console.error('Collection Index Out of Range');
		return; // current page not found in collection – abort
      }
      const prevBtn = document.getElementById(prevBtnId);
	  const prevLink  = prevBtn.querySelector('a');
      const nextBtn = document.getElementById(nextBtnId);
	  const nextLink  = nextBtn.querySelector('a');

      // Previous link
      if (slugs[idx - 1]) {
        prevLink.href = `/${collectionSlug}/${slugs[idx - 1]}`;
      } else {
        prevBtn.style.display = 'none';
      }

      // Next link
      if (slugs[idx + 1]) {
        nextLink.href = `/${collectionSlug}/${slugs[idx + 1]}`;
      } else {
        nextBtn.style.display = 'none';
      }
    })
    .catch(err => console.error('Navigation fetch error:', err));
});
</script>
2 Likes