Check when an element is visible
by jashwant
HTML
<div id='parent'>
<div class='some-text'>
Some text
</div>
</div>
CSS
.some-text {
margin-top:1000px;
padding-bottom:200px;
background: red;
}
JavaScript
var scrollEventHandler = function() {
if(isScrolledIntoView(document.getElementsByClassName('some-text')[0])) {
$('.some-text').text('Scolled completely into view');
unbindScrollEventHandler();
} else {
$('.some-text').text('Some text');
}
}
function unbindScrollEventHandler() {
$(document).unbind('scroll', scrollEventHandler);
}
$(document).scroll(scrollEventHandler);
function isScrolledIntoView(el) {
var elemTop = el.getBoundingClientRect().top;
var elemBottom = el.getBoundingClientRect().bottom;
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
return isVisible;
}