Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - check if elements come into view, fade in those that do

I have found the answer to this issue when I know which element to specify, but what I am looking for is for a way to check 'on scroll' whether ANY element with a specific class has come into view, and modify them as they do (e.g. change opacity - only those that come into view). I know the code might look something similar to this, but I can't make it work:

jQuery(window).on("scroll", function() {
var difference = jQuery(window).offset().top + jQuery(window).height()/2;
if (difference > jQuery(".makeVisible").offset().top) {
     jQuery(this).animate({opacity: 1.0}, 500);

}
});

Thank you very much. Note: the variable difference exists because I want elements to become visible as they reach the middle of the screen.

like image 271
cVergel Avatar asked Mar 28 '14 05:03

cVergel


1 Answers

Borrowing from Check if element is visible after scrolling and Using jQuery to center a DIV on the screen to check if the element is in the viewable center of the screen:

function isScrolledIntoView(elem)
{
    var centerY = Math.max(0,((jQuery(window).height()-jQuery(elem).outerHeight()) / 2) 
                  + jQuery(window).scrollTop());

    var elementTop = jQuery(elem).offset().top;
    var elementBottom = elementTop + jQuery(elem).height();

    return elementTop <= centerY && elementBottom >= centerY;
}

We can then modify your approach to:

jQuery(window).on("scroll resize", function() {
    jQuery(".makeVisible").each(function(index, element) {
        if (isScrolledIntoView(element)) {
           jQuery(element).animate({opacity: 1.0}, 500);
        }
    });
});
like image 154
Nathan Avatar answered Oct 18 '22 18:10

Nathan