The following function checks if a given element is within browser's viewport:
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
Sample Usage
On this example I'll be loading iframes only when they are on the browsers viewport. For this to work I initially printed all iframe's without the SRC attribute. Instead, I used the REL attribute as a placeholder for the iframe destination:
var my_interval = setInterval(checkIframesVisibility, 1000);
function checkIframesVisibility()
{
$("iframe").each(function(i) {
if (isScrolledIntoView($(this)))
{
if ($(this).attr('src') == "")
{
$(this).attr('src', $(this).attr('rel'));
$(this).iframeAutoHeight({debug: false, diagnostics: false});
}
}
});
}
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
PS: The iframeAutoHeight is a plugin that auto resizes the iframe to the content's height.
Hope you find this is useful!
