views:

41

answers:

2

In javascript is it possible to trigger an action when a element (for example a div) is shown in the screen?

I have an "endless" grid that extends both horizontally and vertically, and I would like to load the elements dynamically using AJAX while the user scrolls.

Thanks

+3  A: 

you can check if the scrollbar is near the end with something like this (i assume you're using jquery):

$('#my-container').scroll(function(e) {
  var tolerance = 0;    
  var $el = $(this);
  if ($el[0].scrollTop + $el.height() >= $el[0].scrollHeight - tolerance) {
   // do your ajax stuff
  }
});

EDIT: you can check if an element is in the viewport with viewport plugin (or better, you can apply the same logic used there to any container other than window)

gpilotino
Thanks gpilotino, but this would mean to load a full row or column instead of individual elements of the grid. I want to avoid loading a full column as the grid can get very big!
Victor P
i think in that case you have to check both horizontal and vertical at the same time. practically you have to check that the "visibile" element scrollTop/Left are inside the viewport (the window.scrollTop/Left/height/width)
gpilotino
+1  A: 

You can use document.body.scrollTop and document.body.scrollLeft to know the position of the scroll.

P.S: gpilotino was faster and actually posted some useful code

Sergi