W3docs

How to Check if Element is Visible after Scrolling

Read the tutorial and find out one of the methods of checking whether the element is visible after scrolling with jQuery. Also, find about utility function.

You can check if an element is visible after scrolling using jQuery. This approach assumes there is no horizontal scrolling.

You can get the window's top position using <kbd class="highlighted">$(window).scrollTop()</kbd>, and <kbd class="highlighted">$(window).height()</kbd> for the height.

To get the element's top position, use <kbd class="highlighted">$(elem).offset().top</kbd>, and <kbd class="highlighted">$(elem).height()</kbd> for its height.

Check visibility with jQuery

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
    <style>
      .largebox {
        height: 1500px;
      }
      .box {
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div class="largebox">
      <div id="msg" style="position:fixed;left:30%;"></div>
      <div class="box">First box</div>
      <div id="box1" class="box1">Second box</div>
    </div>
    <script>
      function isVisible($el) {
        let docViewTop = $(window).scrollTop();
        let docViewBottom = docViewTop + $(window).height();
        let elTop = $el.offset().top;
        let elBottom = elTop + $el.height();
        return((elBottom <= docViewBottom) && (elTop >= docViewTop));
      }
      $(function() {
        $("#msg").text("#Second box  visible=" + isVisible($("#box1")));
        $(window).scroll(function() {
            $("#msg").text("Second box visible=" + isVisible($("#box1")));
          });
      });
    </script>
  </body>
</html>

You can also use a utility function that accepts an element and checks if it is fully or partially in view:

Utility function for viewport checks

function Utils() {
  //...
}
Utils.prototype = {
  constructor: Utils,
  elementInView: function (el, fullView) {
    let pageTop = $(window).scrollTop();
    let pageBottom = pageTop + $(window).height();
    let elTop = $(el).offset().top;
    let elBottom = elTop + $(el).height();
    if (fullView === true) {
      return ((pageTop < elTop) && (pageBottom > elBottom));
    } else {
      return ((elTop <= pageBottom) && (elBottom >= pageTop));
    }
  }
};
const utilsInstance = new Utils();

Using the utility function

let elementInView = utilsInstance.elementInView($('#flyoutLeftContainer'), false);
if (elementInView) {
  console.log('In view');
} else {
  console.log('Out of view');
}

This approach relies on the window's scroll position.