0

The code that I am currently using displays 4 divs at a time and loads 4 more divs when the user clicks on the "Load more" button.

<script>
$(function() {
  $(".post").slice(0, 4).show();
  $("#loadMore").on('click', function(e) {
    e.preventDefault();
    $(".post:hidden").slice(0, 4).slideDown();
    if ($(".post:hidden").length == 0) {
      $("#load").fadeOut('slow');
    }
  });
});
</script>

How would I edit this so that four new divs are automatically displayed when the user scrolls to the bottom of the parent div rather than clicking the button.

The first four divs that are loaded should be due to the user clicking on the button and from then on should load once the user scrolls to the bottom of the parent div.

<div class="contents">

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

</div>
  • You might want to look at this: [Detecting when user scrolls to bottom of div with jQuery](http://stackoverflow.com/questions/6271237/detecting-when-user-scrolls-to-bottom-of-div-with-jquery) – prashkr Jun 23 '16 at 20:29

1 Answers1

0

This function allow you to check if a percentage of a given node is visible on the screen.

function isVisible (node, percentage) /* 0.50 = 50% */
{
    var rect = node.getBoundingClientRect();
    var over = rect.height * (1 - percentage);

    return rect.top >= -over && rect.bottom <= window.innerHeight + over;
}

window.addEventListener
(
    "scroll", function ()
    {
        var myParentDiv = document.querySelector("") // here obtain your parent div

        if (isVisible(myParentDiv, 1))
        {
            // when the parent div is 100% visible in the viewport, append your 4 elements.
        }
    }
);

This is an example, after you appended the 4 elements you have to remove the listener.

user123123123
  • 318
  • 2
  • 7