Infinite Scroll without Plugin (With CSS and jQuery Only)

Coding

Filed Under: Code Snippets


Simple example to add Infinite Scroll or Load More button to display more content without page refresh. It can be use for Blog posts, Portfolio items, Testimonials or for any other purpose according to your requirements.

Below is the sample HTML markup

Advertisement
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<a href="" class="load-more">Load More</a>

By default we’ll hide above ‘div’ items by CSS.

.item{
display:none;
}

Now, time to add some jQuery where the real magic is, don’t forget to add jQuery before below script.

Advertisement
$(function () {
$(".item").slice(0, 1).show();
$("body").on('click touchstart', '.load-more', function (e) {
e.preventDefault();
$(".item:hidden").slice(0, 1).slideDown();
if ($(".item:hidden").length == 0) {
$(".load-more").css('visibility', 'hidden');
}
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
});

As we hide items div earlier by CSS, the above script is displaying 1 item at page load, on Load More button click, it shows one more item (You can change the numbers according to your requirements). And when there’ll be no more item left, it’ll hide the “Load More” button.

Also Read:


Tags: , , , ,



Leave a Reply

Your email address will not be published. Required fields are marked *