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.
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With