-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathloadMorePosts.js
56 lines (47 loc) · 1.98 KB
/
loadMorePosts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
})
})