Barry
Barry

Reputation: 57

JS Add Class On Scroll

– – – – – Update – – – – –

Hi there, I have replaced the following code if (isScrolledIntoView(this) === true) { with this code if (scroll >= 500) { but the class is no longer being added. Also, wouldn't 500 be a pixel value as opposed to a percentage of the viewport height? Also, would this solution help with my first issue described below?

If I should have put these two queries in two separate questions, please let me know. I've only every posted single issue queries in the past.

Thanks.

– – – – – End Update – – – – –

Looking for a bit of Javascript help, I'm currently adding a class to an element when it's scrolled into view but am having a couple of issues.

The first issue is that when the element is vertically larger than the viewport height, the class does not get added.

The second issue is that the class is getting added when the element is halfway down the page, I'm looking to find out if there is a way to add the class when is element is scrolled into view further up the page? Ideally I'd like to specify this value as a percentage of the viewport height as the site I'm building is responsive. Is this possible?

$(window).scroll(function () {
    $('.fade').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('fadeInTransition')
        }
        else{
            //$(this).removeClass('fadeIn')
        }
    });
});
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));
}

Thanks for your time

Barry

Upvotes: 0

Views: 2669

Answers (1)

rodelm
rodelm

Reputation: 341

This has been already addressed:

Add/remove class with jquery based on vertical scroll?

just simply replace 500 with your estimate

Upvotes: 1

Related Questions