The function isScrolledIntoView()
used below is from another question Check if element is visible after scrolling
Explanation of Example
First off we have the function isScrolledIntoView()
which simply returns true
or false
if an element is visible inside your browsers viewing area.
You need to use two divs or some kind of anchor point and a follow div. Your anchor div is used to determine when we should switch the follow div to a fixed style to follow on scrolling or switch back to an absolute position if the anchor is back in view to return the follow div to its original position on the page.
With your anchor point, following div, the function to check if an element is visible in the viewing area, we can make use of the jQuery .scroll()
event binding method on the window to fire an event when the user scrolls on the page.
Example Script
$(window).scroll(function () {
if (! isScrolledIntoView($('#anchor')))
{
// anchor div isn't visible in view so apply new style to follow div to follow on scroll
$('#follow').css({ position: 'fixed', top: '10px' });
}
else
{
// anchor div is visible in view so apply default style back to follow div to place in default position
$('#follow').css({ position: 'absolute', top: '100px' });
}
});
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));
}
Fiddle demo