'Javascript function triggered at the top of the page instead of the bottom

I have this function called getData() that get data from the server with an ajax call; everything works fine, the only one problem is that the function getData() is called when i scroll back to the top instead of gettin called when i reach the end of the page.

Fun fact, I was working on this a week ago and everything worked fine.

Here's the snippet of Javascript:

    $(window).scroll(function(){
    if($(window).scrollTop() == $(document).height() - $(window).height()){
    getData();
    console.log('bottom');
    }
    });

Edit: I found this snippet and this seems to work, very strange.

    window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) 
{
 getData();
}

};

This is my html page:

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 results"></div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script type="text/javascript">
var start = 0;
var limit = 15;
var reached_max = false;

$(document).ready(function() {
    getData();
});


function getData() {
    if (reached_max)
        return;

    $.ajax({
        url: 'data.php',
        method: 'POST',
        dataType: 'text',
        data: {
            getData: 1,
            start: start,
            limit: limit
        },
        success: function(response) {
            if (response == "reached_max")
                reached_max = true;
            else {
                start += limit;
                $(".results").append(response);
            }
        }
    });
}


window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    getData();
}
};


/*
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
getData();
console.log('bottom');
}
});
*/
</script>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source