Mike Rainsbury Mike Rainsbury - 6 months ago 10
Javascript Question

Fade in on scroll - centre of container

I am currently using the following to animate fade in on scroll for some containers on my site, however, as some of my containers have a large height, is there a way to change it so it fades in when the bottom of the window is at the centre of the container rather than at the bottom of the container? Alternatively, is there a way to specify by pixels?

$(window).scroll(function () {

/* Check the location of each desired element */
$('.container').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 it */
if (bottom_of_window > bottom_of_object) {

$(this).animate({
'opacity': '1'
}, 500);

}
});
});

Answer

something like this?

$(window).scroll(function () {

  /* Check the location of each desired element */
  $('.container').each(function (i) {

      var top_of_object = $(this).offset().top;
      var middel_of_window = $(window).scrollTop() + ($(window).height()/2);

      /* If the object is completely visible in the window, fade it in */
      if (middel_of_window > (top_of_object + 300)) {

          $(this).animate({
               'opacity': '1'
          }, 500);

      }
   });
});

Hope it helps you.