JSFiddle - React, Tailwind, and code Playground

by Anonymous

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- scroll right and bottom to locate the blue square -->
<div id="element"></div>
<div id="log"></div>
<div id="log-rect"></div>
<div id="log-el-off"></div>

CSS

body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
#log-rect { position: fixed; left: 0; top: 20px; font: medium monospace; background-color: #EEE8AA; }
#log-el-off { position: fixed; left: 0; top: 40px; font: medium monospace; background-color: #EEE8AA; }

JavaScript

function getViewportOffset($e) {
  var $window = $(window),
    scrollLeft = $(window).scrollLeft(),
    scrollTop = $(window).scrollTop(),
    rect = $e[0].getBoundingClientRect(),
    offset = $e.offset();
    console.log(rect);
  return {
    left: offset.left - scrollLeft,
    top: offset.top - scrollTop,
    bottom: Math.max(document.documentElement.clientHeight, window.innerHeight || 0) - offset.top + scrollTop - rect.height,
    right: Math.max(document.documentElement.clientWidth, window.innerWidth || 0) - offset.left + scrollLeft - rect.width,
    rect: rect,
    offsetWidth: $e[0].offsetWidth,
    offsetHeight: $e[0].offsetHeight
  };
}

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

$(window).on("load scroll resize", function() {
  var viewportOffset = getViewportOffset($("#element"));
  $("#log").text("[viewport offset] left: " + viewportOffset.left + ", top: " + viewportOffset.top + ", bottom: " + viewportOffset.bottom + ", right: " + viewportOffset.right);

  $("#log-rect").text("[bounding client rectangle] left: " + viewportOffset.rect.left + ", top: " + viewportOffset.rect.top + ", bottom: " + viewportOffset.rect.bottom + ", right: " + viewportOffset.rect.right);
    
  $("#log-el-off").text("[element offset] offset width: " + viewportOffset.offsetWidth + ", offset height: " + viewportOffset.offsetHeight);
});