jQuery – check if element is visible in viewport ofter scroll

To check if an element is visible in window viewport after vertical scrolling the following approach can be used using jQuery. Note that this approach assumes that there is no horizontal scrolling. Similar approach can be applied to check visibility in case there is horizontal scrolling.

  1. Window top can be obtained using $(window).scrollTop() and height can be obtained using $(window).height().
  2. Similarly element top can be obtained using $(el).offset().top and its height can be obtained using $(el).height().

Example

Here is the outcome screenshot and code to check if an element is visible in window viewport.
jquery-check-element-visible-in-viewport

<style>.largebox {height: 800px;}</style>

<div id="msg" style="position:fixed;left:30%;"></div>
<div id="box1" class="box">box1</div>
<div class="largebox">box2</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function isVisible($el) {
  var winTop = $(window).scrollTop();
  var winBottom = winTop + $(window).height();
  var elTop = $el.offset().top;
  var elBottom = elTop + $el.height();
  return ((elBottom<= winBottom) && (elTop >= winTop));
}
$(function() {
  $("#msg").text("#box1 visible=" + isVisible($("#box1")));
  $(window).scroll(function() {
    $("#msg").text("#box1 visible=" + isVisible($("#box1")));
  });
});
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments