tags:

views:

29

answers:

2

how can i find the pixel value of the bottom of an element. eg. the #posts div. i want to create a infinite scroller. and this is so that i can detect if the user has reached near/at the bottom of the #posts and i want to load new posts if so.

alt text

update:

i guess 1 option is to use

$("#header").height() + $("#posts").height()

but i want to make the code generic. so maybe i can convert this functionality into a plugin. the code above will not have taken into consideration, padding, margins, any elements above #posts etc.

+2  A: 
var div = $('#posts');
var bottom = div.offset().top + div.height();
sje397
+1  A: 

If you had a <div> inside of #posts with the actual content, you'd do something like this:

$("#posts").scroll(function() {
  if($(this).scrollTop() == ($("#posts_content").outerHeight() - $(this).height())) {
    alert("Reached Bottom!");
  }
});​

You can try a demo here. Upon a .scroll() event, we're checking .scrollTop() of the #pages div to see how far it's scrolled down. If that's equal to the inner-div's .outerHeight() minus the .height() of #pages (because .scrollTop() gives the top position), then we throw an alert.

You can of course do whatever loading you need here, if you want it to load before the very bottom, just change the == to >= and slap a -40 or something on the right side to load 40 pixels from the bottom. Something like this:

$("#posts").scroll(function() {
  if($(this).scrollTop() >= ($("#posts_content").outerHeight() - $(this).height() - 40)) {
    alert("Reached Bottom!");
  }
});​
Nick Craver
i think i need some time digesting this :) i think i am kind of a noob here. the 1st answer by sje397 seems to work fine. and is simple to understand. seems to work well enough for my case at the moment
jiewmeng
@jiewmeng - This is more of a full solution, I misunderstood though, if you want to detect if the *page* has been scrolled (not `#posts` being a scroll window), it'd look like this: http://jsfiddle.net/MknA2/2/
Nick Craver
i wonder if that will work any differently from what i am currently using http://jsfiddle.net/MknA2/5/ i guess yours is shorted but i was just curious
jiewmeng