jQuery load more data on scroll
In jQuery, check whether you have hit the bottom of page using scroll function. Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div. This function gets executed as you scroll down the page again.
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
}
});
How to load more data when scroll from bottom to top jquery \ js
HTML CODE
<div class="chat-list" id="messages" #scrollMe [scrollTop]="scrolltop" (scroll)="onScrollChat()">
<div *ngFor="let message of Chats;let i = index">
</div>
</div>
JS
Here we have note the scrolltop position [old_height] before loading data.Once the data is loaded on scroll we have to get new scrolltop position[new_height]. scrollTop will be ele.scrollTop =
new_height - old_height
*note: don't put style scroll-behaviour:smooth
onScrollChat() {
if (this.selectedTab != 0) {
let ele = document.getElementById('messages');
let old_height = ele.scrollHeight; // getting height before loading more messages
if (ele.scrollTop == 0) {
//call chat api to load more messages
this.tempMsgs = data;//loaded messages
this.Chats = this.tempMsgs.concat(this.Chats)
this.changeDetectionRef.detectChanges();
let new_height = ele.scrollHeight
ele.scrollTop = new_height - old_height;
}
}
}
jQuery load more data on scroll not loading more data
If the loading icon is never removed check the console for any errors. You're setting the loading icon to be shown in the beforeSend
function but have no error
property in the ajax handler.
Remove $("#results").append(html);
from the top of your success: function(html) { .. }
and move it into the else
portion of your if
statement. You do this so you're not attempting to append an empty string, or an unwanted string, for no reason and we have finer control over it via our if/else
logic.
You'll also want to remove $('#loader_image').show()
from the else
statement. You're re-showing it even though the ajax call has been processed successfully.
See the cleaned up success
function below.
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#results").append(html);
}
window.busy = false;
}
New ajax call:
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$('#results').append(html);
}
window.busy = false;
},
error: function(error) {
console.log(error);
$('#loader_image').hide();
$('#loader_message').html('There was an error processing your request.').show();
}
});
Load more posts in a container on scroll with jquery
Since the ajax call takes time (opposed to my attempt to reproduce) and the scroll
event is firing like a machinegun...
The same ajax request could be triggered more than once.
To avoid that, use a flag ajax_request_sent
like so:
// A flag to know if a request is sent and the response is not yet received
let ajax_request_sent = false;
$(window).scroll(function() {
var pjCount = $('.pj-col').length;
var totalPj = $('#pj-numb').val();
if (pjCount >= totalPj) {
return false;
} else {
// Use the flag in the condition (so if sent and not yet received == false)
if (!ajax_request_sent && $(window).scrollTop() >= $('.projects-list-wrap').offset().top + $('.projects-list-wrap').outerHeight() - window.innerHeight + $('header').outerHeight()) {
// Set the flag to prevent any concurring request
ajax_request_sent = true
jQuery.ajax({
url: ajaxURL,
type: "POST",
beforeSend: function() {
$('.projects-wrapper').append("<div class='pj-loader'></div>");
},
complete: function() {
$('.pj-loader').remove();
},
data: {
action: "pj_load_more",
pjCount: pjCount
},
success: function(data) {
$('.projects-list-wrap').append(data);
// Unset the flag
ajax_request_sent = false;
},
error: function(err) {
//console.log(err);
}
});
}
}
});
How to Load data dynamically onscroll with Datable Jquery?
You need to get new record on scroll event
$(function() {
var $mytable = $("#myTable");
var page = 10;
var count = 10; //initial number of rows
var max = 500; //max number of rows (just for demo)
var $datatable = $mytable.DataTable({
"paging": false,
"bFilter": false
}); //init the datatable and return a refence to it
//listen for scroll and resize and custom 'fetchmore' events
$(window).bind('scroll resize fetchmore', function() {
var viewportHeight = window.innerHeight;
var scrolltop = $(window).scrollTop();
var bottomOfTable = $mytable.offset().top + $mytable.outerHeight();
//console.log(viewportHeight, scrolltop, bottomOfTable);
if ($(window).scrollTop() + viewportHeight >= bottomOfTable) {
if (count < max) {
//console.log("Fetch more data!");
load_more();
$(window).trigger("fetchmore"); //keep triggering this event until we've filled the viewport
}
}
});
function load_more() {
//fetch more data here
for(var i = 0;i<= page;i++){
count++;
$datatable.row.add([
count + '.1',
count + '.2 (new loaded)'
]).draw(false);
}
}
//trigger initial fetch
$(window).trigger("fetchmore");
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
</head>
<body>
<table id="myTable" class="display">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.1</td>
<td>1.2 (initial row)</td>
</tr>
<tr>
<td>2.1</td>
<td>2.2 (initial row)</td>
</tr>
<tr>
<td>3.1</td>
<td>3.2 (initial row)</td>
</tr>
</tbody>
</table>
</body>
On scroll load more data from database not working in IE 11
Just tested your code example on IE11 and works perfectly fine. Here is the test code i ran in the browser:
var timer;
$(window).scroll(function(){
if ($(document).height() <= $(this).scrollTop() + $(this).height()) {
if(timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(function() {
alert('bottom of page');
});
}
});
Are there any errors thrown in your console on IE11? Sharing more of the code in question would help, as there is no inherent reason for the example you have given to not work on IE11.
Laravel load more data on scroll with Jquery and AJAX
Found the bug in the code, though I had to use JavaScript's alert method to print the value of $(window).height(), $(document).height() and $(window).scrollTop().
That was when I discovered that I missed the parentheses after $(window).scrollTop.
The corrected code is->
var scroll_position_for_post_load = $(window).height() + $(window).scrollTop() + 100;
if(scroll_position_for_post_load >= $(document).height(){
// rest of code goes here
}
Load more data on scroll
If the API supports pagination then you can use React-Infinite-Scroll. It looks like this
<div style="height:700px;overflow:auto;">
<InfiniteScroll
pageStart={0}
loadMore={loadFunc}
hasMore={true || false}
loader={<div className="loader">Loading ...</div>}
useWindow={false}>
{items}
</InfiniteScroll>
</div>
However if the REST API does not support it, you can still load the data and show them in chunks to the user with the same library but you would need to handle the current load state by yourself.
Related Topics
How to Add New Array Elements at the Beginning of an Array in JavaScript
Node.Js on Multi-Core MAChines
Parseint VS Unary Plus, When to Use Which
Are There Constants in JavaScript
Chrome Desktop Notification Example
Programmatically Lighten or Darken a Hex Color (Or Rgb, and Blend Colors)
Const in JavaScript: When to Use It and Is It Necessary
Binding Arrow Keys in Js/Jquery
How to Add a Custom Right-Click Menu to a Webpage
Javascript: Filter() for Objects
Jquery's Jquery-1.10.2.Min.Map Is Triggering a 404 (Not Found)
How to Set the Value Property in Angularjs' Ng-Options
Callback After All Asynchronous Foreach Callbacks Are Completed
Read Environment Variables in Node.Js
Differencebetween Screenx/Y, Clientx/Y and Pagex/Y
How to Dynamically Change Header Based on Angularjs Partial View