Skip to content

Polyfill: intersectionRatio wrong if root has border #276

@waldbaerkoch

Description

@waldbaerkoch

See the following HTML doc. The root (here the div element with id="outer") has a border (border: 2px solid #000). That results in calculating the wrong intersectionRatio for the second observed element (div element with id="el2"). Only the first observed element should get the class "visible".

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script>
delete window.IntersectionObserver;
    </script>
    <script src="intersection-observer.js"></script>
    <script>
function init() {
  function callback(entries, observer) {
    Array.prototype.forEach.call(entries, function(entry) {
      if (entry.intersectionRatio > 0) {
        entry.target.classList.add('visible');
      }
    });
  }
  var observer = new IntersectionObserver(callback, { root: document.getElementById('outer') });
  Array.prototype.forEach.call(document.querySelectorAll('#outer div'), function(el) {
    observer.observe(el);
  });
}
window.addEventListener('load', init);
    </script>
    <style>
#outer {
  overflow-y: hidden;
  height: 2em;
  border: 2px solid #000;
}
#outer div {
  height: 100%;
}
    </style>
  </head>
  <body>
    <div id="outer">
      <div id="el1">Element 1</div>
      <div id="el2">Element 2</div>
      <div id="el3">Element 3</div>
    </div>
  </body>
</html>

I cross-checked with Chrome, Firefox and Edge (with the delete window.IntersectionObserver; removed). In all three only el1 has the class "visible".

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions