diff --git a/blog/index.html b/blog/index.html index 4fbd1006..cf2be8f8 100644 --- a/blog/index.html +++ b/blog/index.html @@ -2,6 +2,10 @@ title: Blog description: --- + + +{% assign see_more_posts = "See more posts…" %} +{% assign button_class = "common-button common-button--color-red" %}
@@ -21,7 +25,7 @@
-
+
{% for post in paginator.posts %} {% include post.html %} {% endfor %} @@ -29,7 +33,19 @@ {% if paginator.next_page %}
- See more posts… + + {{ see_more_posts }} + +
{% endif %}
diff --git a/blog/loadMorePosts.js b/blog/loadMorePosts.js new file mode 100644 index 00000000..60f0beac --- /dev/null +++ b/blog/loadMorePosts.js @@ -0,0 +1,56 @@ +/** + * loadMorePosts.js + * + * This script enhances the blog pagination functionality by dynamically loading + * more posts when the "See more posts" button is clicked, without refreshing the page. + * It fetches the next page of posts via AJAX and appends them to the existing list. + * Additionally, it updates the URL to reflect the current page state using the History API. + * + */ + +document.addEventListener('DOMContentLoaded', () => { + const loadMoreLink = document.getElementById('loadMorePosts') + + if (loadMoreLink) { + loadMoreLink.addEventListener('click', (event) => { + event.preventDefault() + + const nextPage = loadMoreLink.getAttribute('href') + + fetch(nextPage) + .then((response) => response.text()) + .then((data) => { + const parser = new DOMParser() + const doc = parser.parseFromString(data, 'text/html') + const newPostsContainer = doc.querySelector('#blogPosts') + const newNextPageLink = doc.querySelector('#loadMorePosts') + + // Check if newPostsContainer exists + if (newPostsContainer) { + const newPosts = newPostsContainer.innerHTML + + // Append new posts + document.getElementById('blogPosts').insertAdjacentHTML('beforeend', newPosts) + } else { + throw new Error('New posts container not found.') + } + + // Update the URL using history.pushState + history.pushState(null, '', nextPage.endsWith('/') ? nextPage : nextPage + '/') + + // Update next page link or remove it if no more pages + if (newNextPageLink) { + loadMoreLink.setAttribute('href', newNextPageLink.getAttribute('href')) + } else { + loadMoreLink.remove() + } + }) + .catch((error) => console.error('Error loading more posts:', error)) + }) + } + + // Treat back/forward navigation as a page reload to fetch the correct page + window.addEventListener('popstate', () => { + window.location = window.location.href + }) +})