0

I have a snippet that on scroll it checks wether an element is in the current viewport.

I now want to add multiple elements into the mix, but I wanted to avoid doing multiple if statements checking for each, I know the following code doesn't work but it is an example of how I would like to do it, is there a way of doing it this way?

var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');

$(window).scroll(function(event) {
  // if the element we're actually looking for exists
  if (listOfPanels.length){

    // check if the element is in the current view using the attached function
    // and the event hasn't already fired
    if (isElementInViewport(listOfPanels)) {

      // do something
    }
  }
});
rogy
  • 440
  • 6
  • 23
  • http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433: check this answer which is really helpful. – Jai Dec 03 '14 at 10:19
  • @Jai I alreday have the viewport snippet, its the multiple elements I am struggling with – rogy Dec 03 '14 at 10:23

1 Answers1

1

try this:

function isElementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}

var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
  if (listOfPanels.length){
    listOfPanels.each(function(){
      if (isElementInViewport($(this)[0])) {
        console.log($(this).attr('id') + ' in viewport');
      }
    });   
  }
});

hope that helps.

Community
  • 1
  • 1
geevee
  • 5,411
  • 5
  • 30
  • 48