0

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

Victor
  • 23,172
  • 30
  • 86
  • 125
  • This question may be of interest as well. http://stackoverflow.com/questions/704758/how-to-check-if-an-element-is-really-visible-with-javascript – Nosredna Nov 15 '09 at 23:56

2 Answers2

3

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
  • 13,055
  • 9
  • 48
  • 61
  • 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 Nov 15 '09 at 23:59
  • 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 Nov 16 '09 at 00:11
1

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
  • 2,872
  • 2
  • 25
  • 24