tags:

views:

45

answers:

1

So I have a JS function that displays a widget at the bottom of the page. The JS function makes a call to the server to get information to display but I have a theory that most of the people on certain pages never scroll down to even see the widget so i don't want to waste the bandwidth and cycles to render it if it's not going to be seen. Is there a way I can load it when it comes into view? As in, if the user scrolls down to Y then the JS function loads up?

+1  A: 

May be this is what you are looking for:

http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/

Here is the demo page for the above:

http://www.webresourcesdepot.com/dnspinger/

Quoting from the above source:

This would tell you if the user is at the bottom of the page (hence new content has to be loaded). It uses jQuery.

if  ($(window).scrollTop() == $(document).height() - $(window).height())
{
   // do your loading content code
}

EDIT

If your widget is to be located somewhere else, you could do something like this:

if  ($('#widget').position().top == $(window).scrollTop())
{
   // do your loading within the widget here
}

This would tell you if the scrolled position is where the widget is located.

aip.cd.aish
Cool, what if it's not at the bottom of the page though? The widget is placed in a random location on different pages so it could be in the middle.
Ryan Detzel
One note, with jQuery the .position() is relative to the offsetParent. So if you've got an element within a position:relative or position:absolute element, you're going to have to take the parent element's position into account. If you don't, you'll notice your position() coordinates are too high up on the page.
Rocketmonkeys