0

 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, P.S div height is not static It can be increased, depending on the content, any solution?

Nightcrawler
  • 943
  • 1
  • 11
  • 32
  • 2
    Have you seen the [intersection observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)? Easy way to compare an element’s position relative to the viewport. – D M Jan 24 '21 at 21:20
  • 1
    Try this one... https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery – thisiszammy Jan 24 '21 at 21:24

1 Answers1

1

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>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25