Implementing Infinite Scroll in existing website - javascript

We are trying to implement infinite scroll in our existing website. Currently we have a image 'click for more' and it makes a ajax call to a method GetArticlesFromNextSection(true) which returns data which we append in #sectionArticles. And this works perfect.
Now we are trying to make it automatic as when user reaches at the end it should make a call to GetArticlesFromNextSection(true) method to load next chunk. Here is what we are using:
<script type="text/javascript">
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('#lnkShowMore1').trigger('click'); //click image or
//GetArticlesFromNextSection(true);
}
});
</script>
The problem with above code is, it makes continuous call to method GetArticlesFromNextSection(true) until no data left to load from database. It should make a single call to method GetArticlesFromNextSection(true) and stop and when user tries to scroll again, it should next chunk.
How to make this possible?
EDIT
I used flag but it loads just one time and never again. This is not infinite loop, it should load another chunk again when user reaches end. This is what I used:
<script type="text/javascript">
var is_loading = false;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height() -300) {
if (is_loading) {
return;
}
is_loading = true;
//$('div#more').show();
$('#lnkShowMore1').trigger('click'); //click image or
//GetArticlesFromNextSection(true);
//$('div#more').hide();
}
});
</script>

Take a look at the answers for How to rate-limit ajax requests?
You can either include and use Underscore's _.throttle() in your script, or take a look at how they implement it and adapt into your code instead of including the whole library for a single purpose.
EDIT:
Using Underscore, your code might look like this:
<script type="text/javascript">
$(window).scroll(_.throttle(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('#lnkShowMore1').trigger('click');
}
}, 1000));
... which should rate-limit the requests to once every second.

You can set a flag that check if the content is loaded.
<script type="text/javascript">
$(window).scroll(function () {
if (!isLoading && $(window).scrollTop() == $(document).height() - $(window).height()){
isLoading = true;
$('#lnkShowMore1').trigger('click'); //click image or
//GetArticlesFromNextSection(true);
}
});
</script>
And inside Ajax callback sets
isLoading = false;

Related

HTML Load elements in a blank page

I have an empty HTML page with just a div and a button to load data.
<body>
<div id="main_div"></div>
<button class="load_more" onclick="myFunction()">Load More..</button>
</body>
myFunction is a function which creates and populate the div main_div.
I want to create an infinite scroll view out of it.
I have added scroll listener which call myFunction and loads the data once only 200px is left. (I got this code from a blog online)
$(window).on('scroll', function() {
console.log('Scroll detected')
var scrollHeight = $(document).height();
var scrollPos = Math.floor($(window).height() + $(window).scrollTop());
var isBottom = scrollHeight - 200 < scrollPos;
if (isBottom && currentscrollHeight < scrollHeight) {
$('.load_more').click();
currentscrollHeight = scrollHeight;
}
});
The infinite scroll works fine when I manually tap the load button a few times and the page is loaded with elements. After that when I scroll, it loads new data.
But what I want is to fill the initial space from the same API.
I thought of calling the same function multiple time, but I am not sure how many times should I call, as the page can be opened from a mobile or any browser and I would not know the height of that.
Also, I want to avoid JQuery or other frameworks to keep it minimal. I know the code is already using JQuery, but I plan to remove it.
you can call a function which will check your div height and compare it with windowHeight. Till div height less than windowHeight you should call that function
Like
document.addEventListener("DOMContentLoaded", function(e) {
function loadData(callBackFunction) {
// your function body
// in your ajax success request add following line
if (callBackFunction) {
callBackFunction();
}
}
function loadInitialData() {
if (document.getElementById('main_div').getBoundingClientRect().height < window.innerHeight) {
loadData(loadInitialData);
}
}
(function() {
loadInitialData();
})();
// Also Your click event won't work here(inside the listener function).
// So it isn't visible outside of this function's scope.
// If you want to call the method directly 'from the button', then you have to attach it to `window`
window.loadData = loadData;
})

I just want a simple load data (div) on scroll function

I've been looking around for a simple load data on scroll before the bottom of page.
I'm looking for one just like what revolt dot tv have implemented on their home page.
I found one http://jsfiddle.net/YM5dp/270/
function loadMore()
{
console.log("More loaded");
$("body").append(".div");
$(window).bind('scroll', bindScroll);
}
function bindScroll(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).unbind('scroll');
loadMore();
}
}
$(window).scroll(bindScroll);
but I cant seem to implement it on my site
i'am not sure why my div isn't being triggered.
My homepage continuous to load all divs at once. http://img.studio-heads.net/
Try this:
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
//Add something at the end of the page
}
});
I saw you page. I guess you are calling a jquery function before the jquery library is being loaded. Please add the jquery library before the script call.
Uncaught ReferenceError: $ is not defined
Means that $ isnt initialized and hence jquery is not loaded.

Infinite scroll javascript not running

I'm trying to add infinite scroll functionality to a page using code given in this question, Check if a user has scrolled to the bottom, but nothing happens when I scroll to the bottom of the page. Here is the code so you don't have to follow the link:
<script type="text/javascript">
alert("popup!");
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
alert("bottom!");
}
});
</script>
I added in the first alert to check if it was simply my browser blocking alerts, but it displays fine. The server also has JQuery 1.7.2 min installed and the page is masonry correctly, so I don't think it is an installation problem.
After your reply to my comment, you said you are getting
In the console tab I'm getting Uncaught ReferenceError: $ is not defined
I'm guessing then, that you havent included jQuery in the header of your page (this needs to be in the <head> of each page)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
This will tell you if JQuery has sucessfully loaded on your page
if (typeof jQuery != 'undefined') {
alert("jQuery library is loaded!");
}else{
alert("jQuery library is not found!");
}
Original comment:
try putting console.log($(window).height()+"<-current sctoll | target->"+($(document).height() - 100)) in that loop, open it in chrome and right click -> element inspector, open the console tab, that will tell you what the values are each loop, should help you diagnose the problem. If you don't get any traces, the event is not firing
Perhaps the scroll event is firing properly with the syntax you have there, try this:
$(window).on('scroll', function () {
if ($(window).height() + $(window).scrollTop() >= $(document).height() - 100) {
alert('do stuff');
}
});

element size using javascript - need to recalculate height as JSON data is filtered

var height = $("#mainbody").height();
$("#leftnav").css({"height":height});
$("#leftnav").css({"min-height":height,"padding-bottom":"15px","height":"auto"});
if($.browser.msie && $.browser.version < 7){
$("#leftnav").css({"height":height});
$("#leftNavSearch ul li").each(function(){
if($(this).height() < 20){
$(this).css({"height":"20px"});
}else{
$(this).css({"height":"auto"});
}
});
}else if($.browser.msie && $.browser.version > 7){
$("#leftnav").css({"height":"auto"});
}
The above function calculates the height of the #mainbody and #leftnav matches it.
However, as you filter through the JSON data on the page, you end up with a lot of white space on the bottom.
What would be the best method to recalculate the height, as the filter links are selected?
First you should include Ben Alman's great throttle plugin, which we will use limit the rate the resize function gets called.
Next thing we take your script and put it into a function
function resize_left_nav(){
//YOUR SCRIPT GOES HERE
}
After this we setup a custom event on the leftnav, which we will trigger to resize the column. We use throttle to limit the rate the resize_left_nav function gets called
$('#leftnav').bind('resize-column',function(){
$.throttle(250, resize_left_nav);
});
We want to trigger this event on two occasions:
on page load
$(function(){ $('#leftnav').trigger('resize-column'); });
when the item list gets updated. Just tirgger the event, when your filtering has completed.
To clean everything up a bit, we can wrap the whole code in an IIFE (Immediatly invoked function expression) like this:
(function(){
function resize_left_nav(){ ... }
$('#leftnav').bind( ... );
$(function(){ ... });
})();

How to load the web page content based on user scrolling

How to load the content while user scroll the web page. How to implement this?
Generally speaking, you will need to have some sort of structure like this
....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
<div id="placeHolder"></div>
Then, you will need to detect when you are getting close to the end of the page, and fetch more data
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
AddMoreContent();
}
});
function AddMoreContent(){
$.post('getMoreContent.php', function(data) {
//Assuming the returned data is pure HTML
$(data).insertBefore($('#placeHolder'));
});
}
You may need to keep a javascript variable called something like lastId which stores the last displayed id and pass that to the AJAX receiver so it knows which new content to return. Then in your AJAX you could call
$.post('getMoreContent.php', 'lastId=' + lastId, function(data) {
//Assuming the returned data is pure HTML
$(data).insertBefore($('#placeHolder'));
});
I did exactly this on my company's search page.
Just to expand on Dutchie432. In my experience the
if ($(window).scrollTop() == $(document).height() - $(window).height())
may not be true consistently( personally i couldnt make it true cause it was jumping numbers ).
Also, if the user scrolls up and down it could fire many requests , while we are waiting for the first ajax call to return.
So what i did to make it work, was to use >= instead of == .
Then, unbinding the scrollTop before making my ajax request.
Then binding it again if the ajax has returned any data (which means there may be more).
Here it is
<script type="text/javascript">
$(document).ready(function(){
$(window).bind('scroll',fetchMore);
});
fetchMore = function (){
if ( $(window).scrollTop() >= $(document).height()-$(window).height()-300 ){
$(window).unbind('scroll',fetchMore);
$.post('ajax/ajax_manager.php',{'action':'moreReviews','start':$('.review').length,'step':5 },
function(data) {
if(data.length>10){
$(data).insertBefore($('#moreHolder'));
$(window).bind('scroll',fetchMore);
}
});
}
}
</script>
`
You are referring to Dynamic Progressive Loading.
Is a pretty well documented concept and there is even some built-in support for it from different libraries. JQuery actually has a GridView that supports progressive loading pretty easily for example.
You will need to utilize AJAX to implement this feature.
You can use window.addeventlistener to track the scrolling behavior the webpage and load more content to the page when the user is at the foot of the webpage.
document.documentElement.scrollTop, document.documentElement.clientHeight and document.documentElement.scrollHeight will help you achieve this goal.
for example:
window.addEventListener('scroll',()=>{
const {scrollTop,clientHeight,scrollHeight} = document.documentElement;
if ((scrollTop+clientHeight)>=scrollHeight) {
getContent((current_page+1));
}
});
You can use jscroll a jquery plugin
http://jscroll.com/
You can use some library like jQuery to retrieve the content , then append it to the page content, Or you can use some jquery plugin like this: http://gbin1.com/technology/jquerynews/20111017jquerypluginwaypoints/infinite-scroll/
//Vanilla JS
let isLoaded = false;
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (
document.body.scrollTop > 350 ||
document.documentElement.scrollTop > 350
) {
if (!isLoaded) {
}
} else {
}
}
//jQuery
var isLoaded = false;
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 350) {
if(!isLoaded){
}
}
});

Categories

Resources