HEYHEY
HEYHEY

Reputation: 533

js measuring the difference between visible height and total height of div

How do I measure the total height of the div and visible height on the screen in js?

For example, if the total height of the div is 1000px and currently only 450px are visible on the screen.

Because only 450px is visible and there are still 650px left to be scrolled (remaining px), I am trying to trigger an alert when this remaining px becomes less than 100px.

In other words, out of 1000px, if user scrolls down and the remaining px is less than 100px, I want to trigger an alert.

I see that i can use something like ".offset().top" but I am not so sure how to .

Upvotes: 1

Views: 223

Answers (1)

Przemek
Przemek

Reputation: 3975

var div = document.getElementsByTagName('div')[0];

window.addEventListener("scroll", function() {
  if (window.pageYOffset - div.offsetTop > 900) {
    alert('Less than 100px of div visible');
  }
});
body {
  height: 2000px;
}
div {
  background-color: lightblue;
  height: 1000px;
}
<div></div>

  • window.pageYOffset is current scroll position from top,
  • div.offsetTop is div's position from top

Difference between both is number of pixels scrolled beyond top of the div. More than 900px beyond the top of 1000px-high element means less than 100px of it left.


You can also change that if to

if (window.pageYOffset - (div.offsetTop + div.scrollHeight) > -100) {

div.scrollHeight is height of the div, so the entire above expression stands for number of pixels scrolled beyond bottom of the div. And -100 beyond the bottom means 100px left to it.

Upvotes: 2

Related Questions