Skip to content

Instantly share code, notes, and snippets.

@l4ci
Created January 9, 2018 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save l4ci/2b7ba45d90c584fe3e2958bcc9f94557 to your computer and use it in GitHub Desktop.
Save l4ci/2b7ba45d90c584fe3e2958bcc9f94557 to your computer and use it in GitHub Desktop.
Check if Element is in view
var $window = $(window);
$window_height = $window.height(),
scrollTop = $window.scrollTop();
/**
* Check if element visible in the viewport
*/
var aniElement = $('.animate');
var element_modifier = 0;
function checkIfInView() {
var window_bottom_position = (scrollTop + $window_height);
// Make them animate not when exactly on the bottom of the window
// but move them a little higher before the animation starts.
$.each(aniElement, function() {
var el = $(this),
element_height = el.outerHeight(),
element_top_position = el.offset().top + element_modifier,
element_bottom_position = (element_top_position + element_height);
if ((element_bottom_position >= scrollTop) && (element_top_position <= window_bottom_position)) {
el.addClass('in-view');
} else {
el.removeClass('in-view');
}
});
}
function scrollHelper(){
scrollTop = $window.scrollTop();
checkIfInView();
}
function resizeHelper(){
$window_height = $window.height();
scrollTop = $window.scrollTop();
checkIfInView();
}
$window.on('scroll', scrollHelper);
$window.on('resize', resizeHelper);
$window.trigger('scroll');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment