Facebook loads new posts on timeline and news feed as you scroll down. This makes Facebook home page and profile load faster as Facebook don’t have to load everything on page load. For achieving this Facebook uses a technique called as Infinite scrolling.
In this tutorial we will see how to achieve infinite scroll using pure JavaScript.
What is Infinite Scroll?
Infinite scroll has been called autopagerize, unpaginate, endless pages. But essentially it is detecting when user reaches end of an HTML element i.e., finished reading and then loading new data asynchronous using AJAX and displaying it. Therefore the page seems to load infinitely.
Code Implementation
Here is demo code on how to detect when user reaches end of an element by scrolling
<html>
<head>
<title>Infinite Scroll using JavaScript</title>
</head>
<body>
<div id="timeline">
<div>
Random text
</div>
</div>
<script type="text/javascript">
//detects when user reaches the end
window.addEventListener("scroll", function(){
var wrap = document.getElementById('timeline');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight)
{
//load new content
wrap.innerHTML = wrap.innerHTML + "<div>Random text</div>";
}
})
</script>
</body>
</html>
Facebook always by default displays some number of posts as soon as the page loads. And then other posts are displayed as user scrolls down the page.
In the above example code we are adding some demo text into the content area as user finishes reading i.e., reaches the end of the #timeline
element. Here we are directly adding some random text but in a real website you are supposed to fetch new data using AJAX and then add to the page.
Leave a Reply