let postOffset = 1; // Start at 1 since the first post is already loaded
const maxPosts = 3; // Load up to 3 additional posts
let loading = false;
let categoryID = document.body.dataset.categoryId; // Store category ID dynamically
window.addEventListener("scroll", () => {
if (loading || postOffset >= maxPosts) return;
let scrollY = window.scrollY || window.pageYOffset;
let documentHeight = document.documentElement.scrollHeight;
let windowHeight = window.innerHeight;
if (scrollY + windowHeight >= documentHeight - 200) {
loading = true;
document.getElementById("loading").style.display = "block";
fetch(`/wp-admin/admin-ajax.php?action=load_more_posts&offset=${postOffset}&category_id=${categoryID}`)
.then(response => response.json())
.then(data => {
if (data.success && data.html.trim() !== "") {
let newPost = document.createElement("div");
newPost.innerHTML = data.html;
document.getElementById("post-container").appendChild(newPost);
// Update URL dynamically without reloading
window.history.pushState({}, '', data.new_url);
postOffset++;
loading = false;
} else {
loading = true;
}
document.getElementById("loading").style.display = "none";
});
}
});
// Handle back/forward button behavior to reload content
window.addEventListener("popstate", () => {
location.reload();
});