gaintsev
2/9/2016 - 9:13 PM

jQuery detect element in view on scroll

jQuery detect element in view on scroll

var $animationElements = $('.animate');
var $window = $(window);

function checkIfInView() {
    var windowHeight = $window.height();
    var windowTopPosition = $window.scrollTop();
    var windowBottomPosition = (windowTopPosition + windowHeight);
    $.each($animationElements, function() {
        var $element = $(this);
        var elementHeight = $element.outerHeight();
        var elementTopPosition = $element.offset().top;
        var elementBottomPosition = (elementTopPosition + elementHeight);
        if ((elementBottomPosition >= windowTopPosition) && (elementTopPosition <= windowBottomPosition)) {
            $element.addClass('showing');
        } else {
            $element.removeClass('showing');
        }
    });
}

$window.on('scroll resize', checkIfInView);
$window.trigger('scroll');