简体   繁体   中英

JS detecting div height left below the screen

So, I have a html markup as below:

在此处输入图片说明

There is a div that pretty much covers the whole height of the page. The height however is dynamically generated.

在此处输入图片说明

When user scrolls the div down and if there is 100px left of the div below the viewable screen, I want to trigger an action (for example, alert).

Because screen size varies, I need a way of simply detecting how much of div is left below the screen.

The thing is, I don't want to constantly measure the height change as that may be "hard" on the user end.

One idea is that maybe I will have a "hidden" div at the end of this main div, and when it is in view point, then I will trigger an action.

As you can see, I am not sure what the best way is for this purpose.

If you need clarification, please let me know.

Thanks!

 var div = document.getElementsByTagName('div')[0]; window.addEventListener("scroll", function() { if (window.pageYOffset + window.innerHeight - (div.offsetTop + div.scrollHeight) > -100) { alert('Less than 100px of div remains below viewport'); } }); 
 body { height: 2000px; } div { background-color: lightblue; height: 1000px; } 
 <div></div> 

  • window.pageYOffset is current scroll position from top,
  • window.innerHeight is height of the viewport,
  • div.offsetTop is div 's position from top,
  • div.scrollHeight is height of the div .

Entire if stands for number of pixels scrolled beyond bottom of the div . And -100 beyond the bottom means 100px left to it.

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