javascriptpaginationinfinite-scrolljquery-waypoints

Custom JS only working on the first page of Paginated items


I'm using Waypoints Infinite Scroll to render posts. Using JS I added an event listener on the delete button on 'DOMContentLoaded'. This all works fine on the first page, but not on subsequent pages. Is this possibly because the 'DOMContentLoaded' event isn't retriggered?

I've tried document.onreadystatechange, but the result is still the same.

Here I'm listening for when the pagination link is triggered and this isn't working and is repetitive.

document.addEventListener("DOMContentLoaded", () => {

  // Delete buttons
  let delete_btns = document.querySelectorAll(".delete_btn");
  delete_btns.forEach((btn) => {
    btn.addEventListener("click", (e) => {
      handleDeleteClick(e.target.id);
    });
  });

  // Infinite Scroll link
  let scroll_link = document.querySelector(".infinite-more-link");
  scroll_link.addEventListener("click", () => {
    delete_btns.forEach((btn) => {
      btn.addEventListener("click", (e) => {
        handleDeleteClick(e.target.id);
      });
    });
  });
});

Is there an alternative event that I could listen for?


Solution

  • You should get the new delete_btns (with document.querySelectorAll(".delete_btn")) after the page change. Something like :

    var infinite = new Waypoint.Infinite({
                onAfterPageLoad: function() {
                   let delete_btns = document.querySelectorAll(".delete_btn");
                   delete_btns.forEach((btn) => {
                        btn.addEventListener("click", (e) => {
                        handleDeleteClick(e.target.id);
                        });
                    }); 
                }
            })