Created
August 2, 2021 00:59
-
-
Save hijonathan/39ba10bfa2fc9135aa578e8450066b7e to your computer and use it in GitHub Desktop.
Implementing next/previous post functionality in Webflow with js. See https://www.mokupet.com/resources for a live example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
/* | |
* Heavily based on https://discourse.webflow.com/t/native-linking-to-previous-and-next-post-or-page-using-cms/19525/19 | |
* This one uses regular ol' javascript instead of jQuery. | |
* | |
* # How this script works: | |
* | |
* 1. It looks for a hidden collection on the page and gets all the items in it. | |
* 2. Using the current item, it identifies the items before and after it. | |
* 3. It then looks for the prev and next buttons on the page and updates those with the correct links. | |
* 4. Once updated, the buttons are unhidden. | |
*/ | |
// Wait for Webflow to be ready. Everyone does this but tbh I don't think we should even have to implement next/prev in JS after the page loads. Alas... | |
var Webflow = Webflow || []; | |
Webflow.push(function() { | |
// Change the selectors here. Don't touch anything else if you don't know what you're doing. | |
var selectors = { | |
collectionItemsSel: '#pagination-source a', | |
prevElId: 'collection-pagination-prev', | |
nextElId: 'collection-pagination-next' | |
}; | |
// Define the elements we're going to mess with. | |
var itemsEl = document.querySelectorAll(collectionItemsSel), | |
prevEl = document.getElementById(prevElId), | |
nextEl = document.getElementById(nextElId), | |
currentItemEl, prevItemEl, nextItemEl; | |
// Loop through each collection item. | |
Array.prototype.forEach.call(itemsEl, function(el, index, array) { | |
// Pull out the current collection item. | |
if (el.classList.contains('w--current')) { | |
currentItemEl = el; | |
// Grab the adjacent collection items if they exist. | |
if (index > 0) { | |
prevItemEl = array[index-1]; | |
} | |
if (index < array.length-1) { | |
nextItemEl = array[index+1]; | |
} | |
} | |
}) | |
// Update the on-page links. | |
if (prevItemEl) { | |
prevEl.setAttribute('href', prevItemEl.getAttribute('href')); | |
prevEl.getElementsByTagName('div')[0].textContent = prevItemEl.textContent; | |
prevEl.style.opacity = 'initial'; | |
} | |
if (nextItemEl) { | |
nextEl.setAttribute('href', nextItemEl.getAttribute('href')); | |
nextEl.getElementsByTagName('div')[0].textContent = nextItemEl.textContent; | |
nextEl.style.opacity = 'initial'; | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment