lola_the_coding_girl lola_the_coding_girl - 3 months ago 15
jQuery Question

JQuery find next element after Y coordinate?

Say I have a page of div that all have the same class and I'm currently using .scroll to listen for and retrieve the Y axis coordinate via .scrollTop. What I want to do is target the next div with the classname coming after current .scrollTop/Y position. Is there a way to pass a numerical value to JQuery selector to say "find the next div with

'.my-class'
who's beginning Y position is greater than current Y position"?

Answer

This should about do it for you. Code is commented below.

$(window).on('scroll', function(){
  // with '.my-class'
  $('.my-class').removeClass('active')
  // who's beginning Y position is greater than current Y position
  .filter(function(){
    return $(this).offset().top > $(window).scrollTop();
  }).first()
  // find the next div
  .next()
  // do stuff
  .addClass('active');
}).trigger('scroll');
body {background: #fff;}
.my-class {
  padding: 2em;
  border: 1px solid #eee;
  margin: 1em;
  border-radius: 1em;
}
.my-class.active {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>