JSFiddle - React, Tailwind, and code Playground

by kthornbloom

HTML

<div id="console"></div>
<div id="element1">
    <div id="element2"></div>
</div>

CSS

#console {
    background-color: yellow;
}
#element1 {
			width: 500px;
			height: 100px;
			background-color: lightblue;
			overflow-y: auto;
			padding-top: 150px;
			margin: 45px;
		}
		
		#element2 {
			margin-top: 110px;
      margin-bottom: 400px;
			width: 400px;
			height: 320px;
			background-color: green;
		}

JavaScript

var visibleY = function(el){
  var rect = el.getBoundingClientRect(), top = rect.top, height = rect.height, 
    el = el.parentNode;
  do {
    rect = el.getBoundingClientRect();
    if (top <= rect.bottom === false) return false;
    // Check if the element is out of view due to a container scrolling
    if ((top + height) <= rect.top) return false
    el = el.parentNode;
  } while (el != document.body);
  // Check its within the document viewport
  return top <= document.documentElement.clientHeight;
};

// Stuff only for the demo
function attachEvent(element, event, callbackFunction) {
    if (element.addEventListener) {
        element.addEventListener(event, callbackFunction, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + event, callbackFunction);
    }
};

var update = function(){document.getElementById('console').innerHTML = visibleY(document.getElementById('element2')) 
        ? "Inner element is visible" : "Inner element is not visible";
};
attachEvent(document.getElementById('element1'), "scroll", update);
attachEvent(window, "resize", update);
update();