简体   繁体   中英

How to fire javascript function after scroll to specific div bottom?

 window.addEventListener("scroll", ()=>{ alert('you passed red box bottom') })
 .first-box{height:200px; width:300px; border:1px solid red}.second-box{ height:200px; width:300px; border:1px solid blue margin-top:140px; }
 <div class="first-box"></div> <div class="second-box"></div>

Hi, I am creating simple app using Vanilla JS, And ran into the problem, I have scroll function, which i want to fire only when, user will pass red box bottom, I have tried to use element.offsetBottom , But unfortunately nothing came out, I want to solve this problem only pure javascript, PS div height is not static It can be increased, depending on the content, any solution?

To reach the bottom of the container you want, you need to use parameter scrollHeight of that container. Further, using the condition if you compare the current position of window.scrollY until this position is equal to element.scrollHeight .

 var firstbox = document.querySelector(".first-box"); window.addEventListener("scroll", () => { if (this.scrollY >= firstbox.scrollHeight) { console.log('you passed red box bottom'); } });
 body { height: 5000px; }.first-box { height:200px; width:300px; border:1px solid red; }.second-box { height:200px; width:300px; border:1px solid blue margin-top:140px; }
 <div class="first-box"></div> <div class="second-box"></div>

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