Liz Banach Liz Banach - 2 months ago 5
CSS Question

How do I edit a jQuery animation to appear in the middle of an element?

I am using this code from JS Fiddle to create a fade animation with elements on a web page. Right now, the element fades in once the full element is visible in the window. Is there any way to edit this so I can trigger the fade animation sooner? Ideally, the fade animation would be triggered when only half of the element is visible instead of the entire element.

Here is the JavaScript that triggers this animation:

/* every time the window is scrolled ... */
$(window).scroll( function(){
/* check the location of each desired element */
$('.fade-in').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* if the object is completely visible in the window, fade it in */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},600);
}
});
});
});

Answer

Change the bottom_of_object value to something less then it's original height

var bottom_of_object = $(this).offset().top + $(this).outerHeight() / 3; //we dived by 3 here at the end.
Comments