Created
January 9, 2018 10:09
-
-
Save l4ci/2b7ba45d90c584fe3e2958bcc9f94557 to your computer and use it in GitHub Desktop.
Check if Element is in view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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