I'm loading elements via ajax. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?
EDIT: freakytard solution was right, but I modified it a bit to also check if element is wholly visible
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) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop) );
}
This should do the trick:
function isScrolledIntoView(elem) { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); }
An answer to your update:
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop) );
is the same as the shorter:
return ( (elemBottom <= docViewBottom) && (elemTop >= docViewTop) );
It claims it is an answer. I flagged it as "not an answer", which is rejected.
I usually go through the answers when I happen to visit a famous old post, and flag the unwanted stuff posted as an answer. But the issue is, the post being famous, every 2-3 year old responses might have few upvotes. Probably because of that reason, reviewers tend to reject it, they might be even thinking it's an audit seeing the upvotes (My guess).
I tried flagging it again hoping to find other reviewers but the system doesn't allow that.
Is that an answer? Shouldn't it be a comment to the question? Or am i totally wrong?
OP
's modification is same as the original answer. It is just criticising the OP's modification, the answer is already there. doesn't answer the original question at all...