AJAX autoload on scroll within a HTML5 section
ajax, css, html, javascript, jquery
Solution
Assuming some variation of the following markup:
<div class="container">
<div class="scroll-content">
<p>Scroll container</p>
</div>
</div>
CSS
.container {
position: relative;
height: 400px;
width: 300px;
overflow-y: scroll;
}
.scroll-content {
position: relative;
height: 1200px; /* height just added for illustrative purposes */
width: 300px;
background: #849558;
}
Here's one way to keep track of your scroll position and trigger your ajax call within a certain range:
$('.container').scroll( function() {
var fromtop = $(this).scrollTop(),
height = $(this).find('.scroll-content').innerHeight() - $(this).innerHeight();
// In the above line we're finding the height of the scrollable content
// and subtracting the height of the viewable area (or parent container).
if ((height - fromtop) < 50) {
alert('trigger ajax call');
}
});
`< 50` represents your trigger range. Change it to whatever is most suitable for your application.
The advantage to this method is that after you've loaded in more content, the inner container's height is recalculated.
Here's a Fiddle
Problem
I've been working on a website which auto loads new content from MySQL database on scroll. But the problem is it loads new content even when the scrolling is negligible. I mean it loads new content on scroll not when I reach at the end of a page. The Scroll-able section is within a static frame. jQuery Code: ``` <script type="text/javascript"> $(document).ready(function() { var track_load = 0; //total loaded record group(s) var loading = false; //to prevents multipal ajax loads var total_groups = <?php echo $total_groups; ?>; //total record group(s) $('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group $("#frames").scroll(function() { //detect page scroll if($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page? { if(track_load <= total_groups && loading==false) //there's more data to load { loading = true; //prevent further ajax loading $('.animation_image').show(); //show loading image //load data from the server using a HTTP POST request $.post('autoload_process.php',{'group_no': track_load}, function(data){ $("#results").append(data); //append received data into the element //hide loading image $('.animation_image').hide(); //hide loading image once data is received track_load++; //loaded group increment loading = false; }).fail(function(xhr, ajaxOptions, thrownError) { //any errors? alert(thrownError); //alert with HTTP error $('.animation_image').hide(); //hide loading image loading = false; }); } } }); }); </script> ``` Guys please help me with it. Maybe there's some kind of problem with ` $(window).scrollTop() + $(window).height() == $(document).height()`this part. I want to track the scrolling of the section not the window.