alias51
alias51

Reputation: 8608

How to add a class when visible in browser window

I want to add the class .animated to an element when it scrolls into view.

So far, I have the following code:

function isElementInViewport(elem) {
    var $elem = $(elem);

    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round( $elem.offset().top );
    var elemBottom = elemTop + $elem.height();

    return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {
    var $elem = $('.circle-purple-lighter');

    // If the animation has already been started
    if ($elem.hasClass('animated')) return;

    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('animated');
    }
}

However, this only works in Chrome. Any ideas on how to fix (or another approach) for cross-browser? IE9+

Upvotes: 2

Views: 972

Answers (1)

Deryck
Deryck

Reputation: 7658

This may be of assistance:

jQuery Visible Plugin: https://github.com/teamdf/jquery-visible

Here is a demo of how to use this plugin (that I tested in Chrome and Firefox):

JSFiddle

$(function () {
    var $h1 = $('h1');
    var testVis = function () {
        $h1.each(function () {
            if ($(this).visible()) {
                $(this).addClass('animated');
            } else {
                $(this).removeClass('animated');
            }
        });
    };
    $(window).on('scroll resize', testVis);
    testVis();
});

Upvotes: 2

Related Questions