Skip to content

Instantly share code, notes, and snippets.

@helielson
Last active December 12, 2015 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save helielson/4711362 to your computer and use it in GitHub Desktop.
Save helielson/4711362 to your computer and use it in GitHub Desktop.
jQuery filter to detect if a element or part of it is appearing in the window (viewport)
jQuery.expr[':'].appearing = function(elem) {
var $window = $(window),
windowViewTop = $window.scrollTop(),
windowViewBottom = windowViewTop + $window.height(),
elemTop = $(elem).offset().top,
elemBottom = elemTop + $(elem).height(),
isAppearingFully = ((elemTop >= windowViewTop) && (elemBottom <= windowViewBottom)),
isAppearingBottom = ((windowViewTop > elemTop) && (windowViewTop < elemBottom)),
isAppearingTop = ((windowViewBottom > elemTop) && (windowViewTop < elemBottom));
return isAppearingFully || isAppearingBottom || isAppearingTop;
};
@rafaelverger
Copy link

A little improvement:

var isAppearingFully = ((elementTop >= windowViewTop) && (elementBottom <= windowViewBottom));

@helielson
Copy link
Author

Nice improvement.
Updated :D

@jhuesos
Copy link

jhuesos commented Jun 26, 2013

There's an error in line 9, it should be
#9: isAppearingFully = ((elemTop >= windowViewTop) && (elemBottom <= windowViewBottom)),

@helielson
Copy link
Author

I've fixed it. Thanks @jhuesos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment