0

This code works well, but when I scroll up and down after 4-5 times it crashes and all the elements disappear. Why does this happen and how do I fix it?

$(window).on("load",function() {
    $(window).scroll(function() {
        var winheight = $(window).innerHeight();
            $(".fade").each(function() {
                /* Check the location of each desired element */
                var objectBottom = $(this).offset().top + $(this).outerHeight();
                var windowBottom = $(window).scrollTop() + $(window).innerHeight();

                /* If the element is completely within bounds of the window, fade it in */
                if ( windowBottom > (objectBottom - (winheight*0.65))) { //object comes into view (scrolling down)
                    if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
                } else { //object goes out of view (scrolling up)
                    if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
                }
            });
        }); $(window).scroll(); //invoke scroll-handler on page-load
    });
Barry Michael Doyle
  • 6,372
  • 18
  • 63
  • 110
Marco Romano
  • 424
  • 5
  • 20

1 Answers1

1

Ok, I supposed that your html is something like this: https://jsfiddle.net/szdwwdac/

Sometimes, if you are scrolling fast up and down, when the element is fading out, your if doesn't work well.

if ( windowBottom >= (objectBottom - (winheight*0.65))) { 
       if ($(this).css("opacity")==0) {$(this).fadeTo(300,1);}
} else { //object goes out of view (scrolling up)
       if ($(this).css("opacity")==1) {$(this).fadeTo(300,0);}
}

It's because of the 500ms of animation. One of the solutions can be the eneble/disable for 500ms of the scroll page. You can check this solution: How to disable scrolling temporarily?

EDIT

Another solution can be: add a class "fading" when you are inside your if. Then, in the if, eval if the element hasClass "fading". If not, you can go inside and make the animation.

Community
  • 1
  • 1
thejoin
  • 316
  • 2
  • 8
  • Thank you @thejoin, the html is exactly the same.Your answer more or less work, so the problem still, if you try on your jsfiddle to move up and down the scroll, you will see some block disappear, and not work for few second. I have try to make slowly and in this way work. Need be under 200. – Marco Romano Jan 24 '17 at 13:37
  • Yeah, I know. I tried in JSFiddle 200ms animation and... it's work, yeah, bu it's not too cool. Maybe the best way is to set an intermediate state "fading", when the div start fading in/out. – thejoin Jan 24 '17 at 15:00
  • yes work but is not nice, I think to change it, also with something in meddle not work well. So i have to found other solution. Do you know something? – Marco Romano Jan 25 '17 at 16:39