.addClass on the initially loaded item

advertisements

Situation: I have written a function that detects whether <section> has entered the viewport via scroll, if so .addClass('fadeInUp') else .removeClass('fadeInUp') causing the .animation-element to fade in on the viewport.

Problem: Because the conditional is binded to the scroll function, the 1st <section> that is initially loaded does not .addClass('fadeInUp') until the user scrolls past then scrolls back to the <section>. View JS Fiddle for example

Question: How can I also detect if the initially loaded <section> is in the viewport, then .addClass('fadeInUp'), etc...

Current JS function:

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));
}

$(window).scroll(function() {
    $('.animation-element').each(function() {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('fadeInUp')
        } else {
            $(this).removeClass('fadeInUp')
        }
    });
});

Here is the JS Fiddle of the prototype.


Simply call the same code you call inside the event hander outside the event handler on the page load.

$(function () {

    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));
    }

    function checkElements(selector) {
        $(selector).each(function() {
            if (isScrolledIntoView(this) === true) {
                $(this).addClass('fadeInUp')
            } else {
                $(this).removeClass('fadeInUp')
            }
        });
    }

    $(window).scroll(function() {
        checkElements('.animation-element'); // <-- check on scroll
    });

    checkElements('.animation-element'); // <-- check on page load
}