How to load the web page content based on user scrolling - javascript

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){
}
}
});

Related

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

Infinite scroll return multiple results in IE

I created a simple infinite scrolling for my website which shows more images when scrolling at the bottom. It works great with Chrome but when I test it on Internet Explorer the loader shows results multiple times. I don't know where is the error.
Here is my jQuery code:
$(document).ready(function(e){
$(document).scroll(function(){
if($(window).scrollTop() + $(window).height() == $(document).height()){
var pictureCount = $(".Picture-1A").length;
$.get('ajax/home-pagination.php', {off_set:pictureCount}, function(data){
$("#homeContent").append(data);
});
}
});
});
I send the off_set to the php page which will return the data with the new pictures and append it to the end of the page
this should work:
first implement the cdn of debounce to your page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js"></script>
then
in your scroll function, add the debounce function like this:
$(window).scroll($.debounce(100, function(){ /* function */ }));
Hope this works for you too. :)

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.

Implementing Infinite Scroll in existing website

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;

Execute javascript after page has loaded and scrolled to hashtag anchor

I have a webpage that contains a bunch of parts, all of which can be scrolled to using hashtag links (e.g. www.marie-charlot.be/#weiss).
I know how to execute javascript functions that trigger after the page loads (using $(document).ready, but these generally trigger before the page is scrolled down to the correct part (the #weiss anchor).
how do I execute scripts after the scrolling?
You should use the JQuery plugin Waypoints for this.
Example:
$('.entry').waypoint(function() {
alert('You have scrolled to an entry.');
});
$(document).ready(function() {
var anchorTop = $('#my-anchor').offset().top;
$(document).scroll(function() {
if($(document).scrollTop() >= anchorTop)
yourFunctionHere();
});
});

Categories

Resources