JSFiddle - React, Tailwind, and code Playground

by Augustus Yuan

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
   <div class="fixed-info">
     <p>Is element within viewport of specified percent? (25%)</p>
     <p id="answer"></p>
   </div>
   <div class="box"></div>
</body>

CSS

body {
  background: black;
  width: 1000px;
  height: 1000px;
  position: relative;
}

.box {
  position: absolute;
  left: 40%;
  top: 30%;
  background: red;
  height: 75px;
  width: 200px;
}

.fixed-info {
  position: fixed;
  top: 0;
  left: 0;
  border: 1px solid white;
  width: 300px;
  height: 50px;
  color: white;
}

JavaScript

$(window).scroll(function() {
    $('#answer').text((visible($('.box'), 25)));
    
   });

// Test whether or not the element is in the viewport
  function visible(el, per) {
    //special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    // amount of px viewport needs to see to fire the event
    var elPercentageHeight = rect.height * (per * 0.01);
    var elPercentageWidth = rect.width * (per*0.01);

    //console.log('elPercentageHeight: ' + elPercentageHeight);
    //console.log('elPercentageWidth: ' + elPercentageWidth);
    //console.log('viewportHeight: ' + window.innerHeight);
    //console.log('viewportWidth: ' + window.innerWidth);
    //console.log('rect: ');
    //console.log(rect);

    var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    var viewportHeight = window.innerHeight || document.documentElement.clientHeight;

    //console.log(rect.top >= 0 - elPercentageHeight);
    //console.log(rect.left >= 0 + elPercentageWidth);
    //console.log(rect.left <= viewportWidth - elPercentageWidth);
    //console.log(rect.right <= viewportWidth - elPercentageWidth); 
    //console.log(rect.right >= 0 + elPercentageWidth);
    //console.log(rect.bottom <= viewportHeight + elPercentageHeight);
    
    // if the element is within the viewport 
    // by definition we say if the top, left, and right are within the viewport or the bottom left and right are in the viewport
    
    return (
        (rect.top >= 0 - elPercentageHeight && rect.top <= viewportHeight - elPercentageHeight && rect.left >= 0 + elPercentageWidth && rect.left <= viewportWidth - elPercentageWidth) ||
        (rect.top >= 0 - elPercentageHeight  && rect.top <= viewportHeight - elPercentageHeight && rect.right <= viewportWidth - elPercentageWidth && rect.right >= 0 + elPercentageWidth) ||
        (rect.bottom <= viewportHeight +...