How to Check if Element is Visible after Scrolling

One of the methods of checking whether the element is visible after scrolling is possible with jQuery. This approach considers that there is no horizontal scrolling.

You can get the window top using $(window).scrollTop(), and $(window).height() for height.

For getting element top use $(elem).offset().top, and use $(elem).height() for the height.

<!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 call a utility function which accepts the element you are searching for and makes element be fully or partially in view:

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));
    }
  }
};
let Utils = new Utils();

The usage is the following:

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

This only works if the document is a scrollable element.

Do you find this helpful?

Related articles