0

What I want to do is select the next element below where I am on the page. I want to do this to create a "View next post" function. So, if I am past the beginning of post 2, then I want the function to take me to post 3. Conventional jQuery will ask me which child to use of the parents and by default use the first instance, but I want to select the next post below the top of the screen.

So far I am able to grab the current position of the page using:

var curPos = $('html').offset();
var Posi = String(curPos.top).replace(/-/g, "");

But I'm not sure how to filter a function to only select elements below that position.

Help?

Makaze
  • 1,076
  • 7
  • 13
  • Possible dup http://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scrolling – elclanrs Aug 20 '12 at 22:23
  • That certainly helps, but I need to be able to select elements that are visible rather than just test if they are. – Makaze Aug 20 '12 at 22:39

1 Answers1

1

This would be a great time to extend the selector:

 $.extend($.expr[':'], {
      pos: function(a,i,m){
          if(!m[3]){return false;}
          // whatever logic you need to determine 
          // if element is below document offset
          // goes here, simply make this function return true or false
          return $(a).offset().top >= parseFloat(m[3]);
      }
 });

now you should be able to do something like this:

 $('.className:pos('+curPos+')').foo();

Or you can use .filter which will do something similar

 $('.className').filter(function(){
      // whatever logic you need to determine 
      // if element is below document offset
      // goes here, simply make this function return true or false
      return $(this).offset().top >= curPos;
 }).foo();

The difference is filter occurs only once, while extending the selector is fully reusable.

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164