views:

221

answers:

4

is there any javascript library that provides me with a custom event as soon as a certain element becomes visible in the browser canvas?

the basic idea is, as soon as the last element in a list becomes visible on the screen, i want to load the next 10 elements so that the user does not need to click on the "next page" button. to achieve this, a onBecomesVisible event that fires as soon as the last element is shown would be handy. is there something like this?

Slashdot does its front-page loading this way.

+2  A: 

You may want to look at endless scrolling:

http://plugins.jquery.com/project/endless-scroll

altCognito
+2  A: 

Dustin Diaz (who's really really smart, and you should read more of his stuff) wrote an article in 2007 on detecting when an element has scrolled into view.

Might be exactly what you need.

Scottie
+4  A: 

You could write your own simple plugin using jQuery.

 $.belowViewport = function(elem){
  var port = $(window).scrollTop() + $(window).height();
  return port <= $(elem).offset().top;
 }

 $.fn.onBecomeVisible = function( fn ){
  var obj = this;
  $(window).scroll( function() {
   obj.each( function() {
    if(!$.belowViewport(this) && !$(this).data('scrollEventFired')){
     $(this).data('scrollEventFired', true);
     fn(this);
    }
   });
  });
  return this;
 }

And then use it like this

  $('.elements:last').onBecomeVisible( function(elem){ loadNewElems(); } );

The script will bind fn to each of the matched ellements. The function will be fired when any of the matched elements scrolls into view. The function will also be passed which element has fired the event.

Note that you can not bind this event using live so you will have to rebind it after adding new elements (presuming you want the event on the last one of those too.).

EDIT
I was wrong here, :visible does not return wether or not an element is in the viewport. However I have edited the source so it now does check if an element is in the viewport. The function checks if the element is below the viewport, we assume that if it isn't below the viewport it has been scrolled into view and that we should execute the function.

EDIT2
Tested this in google chrome 1.0, firefox 3.0.10 and IE7

Pim Jager
+1, this is pretty awesome if it works. (fixed the spelling of scroll) -- off to try it out.
altCognito
A: 

An alternative idea is to always use a wrapper function for displaying/hiding everything. In other words, instead of directly doing style.display='none'; or $("#something").hide(); , you always use your own function to which you pass the id of the element.

Then, you can more easily track when an element becomes visible/hidden and set event handles to be run.

Click Upvote
No he is looking for an event that is fired once an element is scrolled into view, not when it is unhidden.
Pim Jager