1

This question seems easy but I cant seem to get the fade effect to work properly, please view the fiddle to see the code, you will notice that the image only fades in when you scroll back up and does not fade out when you scroll down, why does this happen? I don't think I fully understand the code I've written I would appreciate some help.

Here is the jQuery code

var divs = $('.banner');
$(window).scroll(function(){
if($(window).scrollTop()<10){
     divs.stop(true, true).fadeIn(5000);
} else {
     divs.stop(true, true).fadeOut(5000);
 }
});

Thank you in advance!

http://jsfiddle.net/a4FM9/809/

gourlaysama
  • 11,240
  • 3
  • 44
  • 51
cdm89
  • 165
  • 2
  • 12
  • `var divs = $('.banner');` really should be in the event function so that it will always get the current elements, otherwise it will be static and only get the elements that were present at the time the code was executed. – Patrick Evans Jul 29 '13 at 15:38
  • 2
    @PatrickEvans You can't say that *should be in the event function*. It's more than correct to do what he's done in the given example. Without seeing the rest of the code you can't say otherwise. – Reinstate Monica Cellio Jul 29 '13 at 15:38

2 Answers2

1

Demo

var divs = $('.banner');
$(window).scroll(function(){
   if($(window).scrollTop()<10){
         divs.stop(true, true).hide().fadeIn(5000); //added hide before fadeIn
   } else {
         divs.stop(true, true).show().fadeOut(5000); //added show before fadeOut
   }
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Very simply you could just remove .stop(true, true) and it fades in both directions:

Working Example

var divs = $('.banner');
$(window).scroll(function(){
   if($(window).scrollTop()<=10){
         divs.fadeIn(5000);
   } else {
         divs.fadeOut(5000);
   }
});

If you want to have the fade take place after the scroll has stopped you could use a timeout function like so:

Working Example 2

$(window).scroll(function () {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function () {
        var divs = $('.banner');
        if ($(window).scrollTop() <= 200) {
            divs.fadeIn(5000);
        } else {
            divs.fadeOut(5000);
        }
    }, 1000)); //timeout set to 1 second
});

See: yckart's timeout function for more info on this timeout function.

Community
  • 1
  • 1
apaul
  • 16,092
  • 8
  • 47
  • 82