-1

I have a few elements and detect if each of them is currently in the viewport. I'm using this answer for that: Answer

function isScrolledIntoView(elem)
{
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

The problem I have is now, as I'm using a collection of elements because there are a couple which have the same class .box, how can I tweak the snippet to actually return the current visible element out of a collection.

Thanks

Edit:

I tried to return [((elemBottom <= docViewBottom) && (elemTop >= docViewTop)), $(elem, this)]

Community
  • 1
  • 1
supersize
  • 10,844
  • 14
  • 56
  • 108
  • 1
    [`Element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) would help you. – Jai Feb 24 '16 at 13:03
  • The function `isScrolledIntoView()` is supposed to return a boolean. Your return statement is returning an array with a second value equal to `$(elem, this)`. What does this second value refer to? – Adib Aroui Feb 24 '16 at 13:09
  • i think this may b the best answer for your question just thing is you need to check for those elements checked with the function given in the answer http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport – Himesh Aadeshara Feb 24 '16 at 13:12
  • @Jai, he said he has two items with same className `.box` which will is not resolving the issue even with `Element.getBoundingClientRect()`. @supersize how are you calling this function (using a loop, jQuery.each()...)? What is the problem of assigning two different ids to the `.box` items? – Adib Aroui Feb 24 '16 at 13:12

1 Answers1

1

Is this helping you?

$( ".box" ).each(function( index ) {
  // for each element you are getting the boolean if is in viewport
  if(isScrolledIntoView(this)) {
     // do something
  }
});

function isScrolledIntoView(elem)
{
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
NiZa
  • 3,506
  • 1
  • 17
  • 27