views:

31

answers:

2

When the top of the body window is greater than or equal to the h2 tag, fade the h2 out, if the top of the window goes back up above that h2, fade that h2 back in.

This code will fade out each individual h2 as you pass it scrolling down, but when i scroll back up, it wont fade it back in, and i'm not sure what i'm doing wrong. i'm not the best at jquery. any help is very appreciated.

$(window).scroll(function() {

 $('.grid_12').find('h2').each(function () {

      if ($(this).offset().top <= $('body').scrollTop()) {
          $(this).fadeOut(500)
      } else if 
          ($(this).offset().top >= $('body').scrollTop()) {
     $(this).prev().fadeIn(500)
         }   
 });
});
A: 

Remove .prev().

SLaks
that didn't do anything, this should be pretty simple... i'm about to punch myself in the face.... seriously.
android.nick
+1  A: 

Try this (demo):

$(window).scroll(function() {
 // added 100 so you can see the fade before it goes out of the viewport
 var bodyTop = $(window).scrollTop() + 100;

 $('h2').each(function() {
  var thisTop = $(this).offset().top,
      faded = $(this).is('.faded');
  if ( thisTop < bodyTop ) {
   if (!faded){
    // fade out h2 if not already faded
    $(this).addClass('faded').animate({ opacity: 0 });
   }
  } else {
   if (faded) {
    // fade in h2 if faded
    $(this).removeClass('faded').animate({ opacity: 1 });
   }
  }
 });

});

Notes:

  • Moved the scrollTop (should be for the window btw) outside of the loop to minimize function calls.
  • Pulled out the $(this).offset().top so it's only called once per loop.
  • Replaced fadeIn/fadeOut with animate since fading results in a display:none (sets dimensions to zero) and thus causes the page to jump when it disappears.
  • Added a "faded" class to prevent repeating animation each time the window scrolls.
  • Removed else if as it is unnecessary.
  • Removed prev() as you should target the h2 and nothing else.
fudgey