jquery – check if you have reached the end of the page with scroll ()

Question:

I am using this jQuery script but it works in reverse

var heightPage = $(document).height();

$(window).scroll(function(){
    if(($(window).scrollTop() + $(window).height()) == heightPage) {
            alert("final de la página");
    }      
});

it is supposed to run the alert when you get to the bottom of the page but it runs it when you get to the beginning

Answer:

I have achieved the goal thanks to a post in English on github the script is as follows:

$(window).on("scroll", function() {
    var scrollHeight = $(document).height();
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        alert("Ha llegado al final de la página");
    }
});

It is a bit more complex (more lines of code and more operations) but in my strange case it worked as I needed, it is an alternative for the same function

Gist link on Github: https://gist.github.com/toshimaru/6102647

Upgrade:

Find the end of the scroll of a div

Lately I had a need for something similar but instead of the whole page I needed to find the bottom of the scroll of a single div.

The code is pure JavaScript

function esElFinal() {
  let element = document.getElementById("scroll");

  if (element.offsetHeight + element.scrollTop >= element.scrollHeight) {
    alert("Llegamos al final del bloque");
  }
}
.container {
  max-height: 100px;
  overflow-y: auto
}

.content {
  height: 100px
}

.red {
  background: red
}

.blue {
  background: blue
}

.green {
  background: green
}
<div onscroll="esElFinal()" id="scroll" class="container">
  <div class="content red"></div>
  <div class="content blue"></div>
  <div class="content green"></div>
</div>
Scroll to Top