12

On a prominent news site (sry, can't remember exactly which one) I saw a really cool effect... when you scroll near the bottom of the page, a new element slides down from the top of the browser viewport with a lot of social media options (tweet, share on facebook, etc). I'd like to emulate something somewhat similar... in fact, there's really a ton of things I could think of to do if I knew how to trigger a function when the user is near the bottom of the page...

So, my question is very basic: how does one trigger a function when the user has scrolled near the bottom of a dynamically sized page?

Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96

2 Answers2

32
$(window).scroll(function () {
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      alert('end of page');
   }
});

-10 indicates how far away from end of page user must be before function executes. This gives you the flexibility to adjust the behavior as needed.

Check working example at http://jsfiddle.net/wQfMx/

Hussein
  • 42,480
  • 25
  • 113
  • 143
9

If you have an element thats near the bottom of the page, you can use Waypoints to trigger a function when the user scrolls to that element. Or if you want to use a pixel limit like in Hussein's post, make sure to heed the scroll lessons we learned from twitter

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
  • It is better to use Waypoints then using Hussein's answer, because Waypoints are cross device compatible while Hussein's answer is working only on PCs. – Airy Mar 03 '14 at 14:42
  • There is nothing in Hussain's answer that would restrict it to work on PCs. Besides, it would be crazy unproductive to use a library for something that can be done in one line of code. – Muhammad bin Yusrat Jan 30 '18 at 07:37