How to make loading items when scrolling?

Where am I wrong? Make loading items when scrolling in the beginning everything works fine when scroll to the end and then starts all loaded from the middle. As it is not correct. The block size of my width: 950px;height: 450px;

Write a script so. But it does not work as needed!

var inProgress = false;
 var startFrom = 42;

 $('#loded').scroll(function () {
 if($('#loded').scrollTop() + $('#loded').height() >= $('#loded').height() && !inProgress) {
$.ajax({
 url: 'obrabotchik.php',
 method: 'POST',
 data: {"startFrom" : startFrom},
 beforeSend: function(data) {inProgress = true;}}).done(function(data){
 data = jQuery.parseJSON(data);
 if (data.length > 0) {
 $.each(data, function(index,data){
 $("#loded").append(`<img style='left: 10px;position: relative;margin-right: 10px;margin-top: 10px;' class='add' data-id='${data.track}'src='//img.youtube.com/vi/${data.track}/mqdefault.jpg' width='120' height='90'>`);
 $('.add').on('click', function () {
 var url = $(this).attr('data-id');
 var u ="http://www.youtube.com/v/"+url+"?version=3";
player.loadVideoByUrl(u);
player.unMute();
});
});
 inProgress = false;
 startFrom += 42;
}});
}

 });
March 19th 20 at 08:45
1 answer
March 19th 20 at 08:47
Solution
Most likely you have the wrong condition:

$('#loded').scrollTop() + $('#loded').height() >= $('#loded').height()


$('#loded').height() will always give 450px, and $('#loded').scrollTop() at the bottom scroll first will be equal to 450px, then 900px, then 1350px and so on.

Try this:
$('#loded').scrollTop() >= $('#loded')[0].scrollHeight - $('#loded').height()


Or look in the direction of ready libraries.

Find more questions by tags JavaScript