6

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.

cVergel
  • 151
  • 3
  • 10

2 Answers2

5

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);
        }
    });
});
Community
  • 1
  • 1
Nathan
  • 10,097
  • 9
  • 59
  • 81
0

I use the skrollr.js plugin to achieve this, which is here on github https://github.com/Prinzhorn/skrollr

Then you can attach parameters to any tags, so for example say you were fading out an image you could have an img tag like

<img src="img/blur/llhs_cake.png" alt="" height="115" width="118" class="overlay" id="llhs_cake" data--bottom-bottom="opacity:0;" data--top-top="opacity:0" data--top-top data--center-center="opacity=1">

with format

data-[offset]-(viewport-anchor)-[element-anchor]

so it's using -- to bypass the offset parameter.

I think this is the easiest way to achieve what you were looking for if you then use jquery to attach it with something like

$('*').attr("data--bottom-bottom="opacity:0;" data--top-top="opacity:0" data--top-center="opacity=1"");

I'm on my mobile so I can't test it right now but I believe it should help, if not might at least give you a new avenue to try!

These sources might help you too: How to update (append to) an href in jquery?

Fade out element, when user reach the bottom of the screen

Community
  • 1
  • 1
HulaHoof
  • 339
  • 1
  • 13