Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if scrolled past div with JavaScript (no jQuery)

Tags:

javascript

I am currently learning JavaScript and all the solutions that I've come across use the jQuery library. Is there a way to do it, just using pure JavaScript?

The idea is to have something like:

function passed(element) {if passed: do something}
like image 376
user3538161 Avatar asked May 29 '16 18:05

user3538161


1 Answers

Listen for the scroll event. To find the current scroll position, you can call the scollY method.

To get the Y coordinate of the top of an element, you can use the element's offsetTop. Because the element has a height, we want to add the height to our calculation.

That's it.

window.addEventListener("scroll", function() {
  var elementTarget = document.getElementById("section-2");
  if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
      alert("You've scrolled past the second div");
  }
});
.section-1 {
  height: 400px;
  width: 100%;
  background: green;
}

.section-3 {
  height: 400px;
  width: 100%;
  background: orange;
}
<div class="section-1"></div>
<div id="section-2">Scroll past this div</div>
<div class="section-3"></div>
like image 163
Richard Hamilton Avatar answered Oct 03 '22 19:10

Richard Hamilton