Are you looking for something like this?
Given this HTML:
<p>a bunch of text, and duplicate this several times. I used lorem ipsum</p>
<p><span id="interesting">Here is the interesting text.</span></p>
<p>a bunch more text, and duplicate this several times. I used lorem ipsum</p>
You can use this JavaScript to display a div when span#interesting
is visible, and hide it when it isn’t visible:
// Add a div to contain a copy of the interesting text
var interestingOffscreen = $('<div/>')
.attr('id', 'interesting')
.text($("span#interesting").text());
$('body').prepend(interestingOffscreen);
// Center the display of that copy
interestingOffscreen.css(
'margin-left',
-(interestingOffscreen.outerWidth() / 2)
);
// Detect when it is offscreen/onscreen and react
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));
}
var isNotVisibleHandler; // forward declaration
function isVisibleHandler()
{
if(isScrolledIntoView($("span#interesting")))
{
$(window).unbind('scroll');
interestingOffscreen.fadeOut(
function() {
$(window).scroll(isNotVisibleHandler);
$(window).scroll(); // force detection
}
);
}
}
isNotVisibleHandler = function()
{
if(!isScrolledIntoView($("span#interesting")))
{
$(window).unbind('scroll');
interestingOffscreen.fadeIn(
function() {
$(window).scroll(isVisibleHandler);
$(window).scroll(); // force detection
}
);
}
};
$(window).scroll(isVisibleHandler);
Not all of this is strictly necessary, but it looks cool.
solved Hide div while an element appear in the browser [closed]