I have an ajax function that gets more posts.
But I would like to trigger it automatically.
My html structure looks like this
<div class="header">
....
</div>
<ul id="grid">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<!-- load more content -->
</ul>
<div>
....
</div>
<div>
....
</div>
<div>
....
</div>
<div>
....
</div>
<div class="footer">
....
</div>
I'm using this code right now.
var count = 2;
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
loadArticle(count);
count++;
}
});
That code trigger ajax function only when the user reach bottom of the page.
Can anyone tell me the proper way to calculate scrolltop?
Use following code
function bindScroll(){
if ($(window).scrollTop() >= $("#grid").height() - $(window).height() - 10) {
// unbind scroll
$(window).unbind('scroll');
//call ajax function
loadArticle(count);
}
}
function loadArticle(count){
....
..Ajax Call ..
....
//bind sroll again
bindScroll();
}
and call bindScroll() function in $(document).ready section to bind scroll event
Ok I used some alternate solution.
I hope it will be useful for others.
<script type="text/javascript">
jQuery(document).ready(function($) {
var count = 2;
$.log(count);
var total = <?php echo $wp_query->max_num_pages; ?>;
$(window).scroll(function(){
if (element_in_scroll("#inifiniteLoader")) {
if (count > total){
$("#inifiniteLoader").css('display','none');
return false;
}else{
$("#inifiniteLoader").css('display','block');
loadArticle(count);
}
count++;
}
});
function loadArticle(pageNumber) {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber,
success: function(html){
$("#og-grid").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
function element_in_scroll(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
});
</script>
#inifiniteLoader {
margin: 20px 0;
display:none;
}
Place this code where you want the loading image.
<div style="text-align:center;" class="clear" id="inifiniteLoader">
<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/loading.gif">
</div>
For loading image check here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.