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.
- Window top can be obtained using
$(window).scrollTop()
and height can be obtained using$(window).height()
. - 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.
<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>