123movies-seo/resources/js/load-more.js

63 lines
2.3 KiB
JavaScript

import LazyLoad from "vanilla-lazyload";
window.lazyFunctions = {
more: function (element) {
const elementHold = element;
const params = JSON.parse(atob(element.dataset.params)),
myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Accept", "application/json");
// console.log(params);
const postBody = {
page: params.page,
route: params.route
};
if ('genre' in params.route_parameters) {
postBody.genre = params.route_parameters.genre;
}
const requestOptions = {
method: "POST",
headers: myHeaders,
body: JSON.stringify(postBody),
// redirect: "follow"
};
fetch(params.route, requestOptions)
.then((response) => response.json())
.then((result) => {
const parentNode = element.parentNode;
parentNode.innerHTML += result.html;
window.lLoad.update();
element.remove();
document.getElementById(element.getAttribute('id')).remove()
if (result.has_more_pages) {
params.page = result.current_page + 1;
elementHold.setAttribute('href', elementHold.getAttribute('href').replace(new RegExp(result.current_page + '$'), result.current_page + 1));
elementHold.setAttribute('data-params', btoa(JSON.stringify(params)));
elementHold.removeAttribute('data-ll-status');
elementHold.classList.remove('entered');
parentNode.appendChild(elementHold);
window.lMore.update();
}
})
.catch((error) => console.error(error));
},
};
function executeLazyFunction(element) {
var lazyFunctionName = element.getAttribute("data-lazy-function");
var lazyFunction = window.lazyFunctions[lazyFunctionName];
if (!lazyFunction) return;
lazyFunction(element);
}
window.lMore = new LazyLoad({
elements_selector: "#next-page",
unobserve_entered: true, // <- Avoid executing the function multiple times
callback_enter: executeLazyFunction, // Assigning the function defined above
});