Adjust InView Element Calculation

I have a way to check if an element is in view or not. How can I determine if a DOM element is displayed in the current viewport? . And try to run a test to check if the elements are in sight or not.

var visibleY = function (el) {
   var top = el.getBoundingClientRect().top, rect, el = el.parentNode;
   do {
      rect = el.getBoundingClientRect();
      if (top <= rect.bottom === false) return false;
      el = el.parentNode;
   } while (el != document.body);
   // Check its within the document viewport
   return top <= document.documentElement.clientHeight;
};

But it returns true for all elements that are below the height of the client element. What changes are needed to complete this work. Fiddle

+4
source share
1 answer

The following answer to this question works if you remove jQuery cruft (which throws an error if you don't have a jQuery global variable):

[deleted code]

Edit

OP, , , , OP . , . , :

// Return true if an element overlaps its parents and the viewport
function isVisible(element) {
  return isInParents(element) && isInViewport(element);
}

// Return true if an element overlaps its parents
function isInParents(el) {
  var rect = el.getBoundingClientRect(),
      rectP,
      visible = true;

  while (el && el.parentNode && el.parentNode.getBoundingClientRect && visible) {
    el = el.parentNode;
    rectP = el.getBoundingClientRect();
    visible = rectInRect(rectP, rect);
  }
  return visible;
}

// Return true if element overlaps the viewport
function isInViewport (element) {

    var rect = element.getBoundingClientRect();

    return rectInRect({top:0, left:0,
                       bottom: window.innerHeight || document.documentElement.clientHeight,
                       right:  window.innerWidth  || document.documentElement.clientWidth
                      }, rect);
}

// Return true if r1 overlaps r0
function rectInRect(r0, r1) {
  return r1.top    < r0.bottom &&
         r1.bottom > r0.top    &&
         r1.left   < r0.right  &&
         r1.right  > r0.left;
}

, , , , - , , .. , , .

, . , .

+2

All Articles