Check Whether element is visible in View port
by Sreeraj Saseendran
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class='page-header' style="height:200px;width:100%; border:3px solid red; position:fixed;top:0;background: lightblue;">
header content
</div>
<div style="min-height:700px;width:100%; border:2px solid blue; margin-top: 200px;">
<p>
test content<br /> test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />test content<br />
</p>
<div style="">
<button class="elementTobeChecked">
test button
</button>
</div>
</div>
JavaScript
function elementVisibleInViewPort(closestVisible, headerElement){
let top_of_element = closestVisible.offset().top;
let bottom_of_element = closestVisible.offset().top + closestVisible.outerHeight();
let bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
let top_of_screen = $(window).scrollTop()+parseInt(headerElement.outerHeight());
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
closestVisible.removeClass('hidden');
if(!closestVisible.hasClass('visible')){
console.log('in');
closestVisible.addClass('visible');
}
} else {
closestVisible.removeClass('visible');
if(!closestVisible.hasClass('hidden')){
console.log('out');
closestVisible.addClass('hidden');
}
}
}
var closestVisible = $('.elementTobeChecked');
var headerElement = $('.page-header');
elementVisibleInViewPort(closestVisible, headerElement);
$(window).scroll(function () {
elementVisibleInViewPort(closestVisible, headerElement);
});