简体   繁体   中英

How to load an ajax only when user scrolls down to that area

We have a website that has a "comments" area we are looking for a way to only begin loading the ajax related to comments once the user actually scrolls down to the comments area.

Many users don't even reach there and we don't want to load the ajax for nothing.

Basically we are loading the comments like this:

$('#commentload').load(<?php echo "'" . base_url() . "ajax/comments'"; ?>);

inside an area called:

<div id="commentload"></div>

What should we add to it so that it only starts the load when user reaches the bottom of the 1/4th bottom of the page?

if(window.pageYOffset>x)将x设置为像素值

You might want to check out appear plugin .

Essentially -

$("#commentload").on('appear', function(event, $element) {
    // ajax call
}

Try following:

var pos = $("#commentload").offset().top;
$( window).scroll(function() {
    var scroll = $(window).scrollTop();
   if(scroll >= pos)
   {
     //Your code
   }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM