Search code examples
javascriptjqueryhtmlcsstoggleclass

javascript onscroll fade same class but with different div


I am really new at JavaScript and I want to learn something new.

There is something wrong with my code : Why my div fades at the same time.

I just want to ask how to fade different divs with same class name.can someone help me and explain that to me.

Thanks in advance.

Javascript:

$(window).scroll(function(){
  if ($( "div.fade" ).offset().top - $(window).scrollTop() <= 100){
       $('.fade').addClass( "fade-in");
  }
  else {
       $('.fade').removeClass("fade-in");
  }
});

here is the JSfiddle


Solution

  • onscroll = function () {
        var scrollTop = $(this).scrollTop() ;
    
        $("div.fade").each(function(){
             if(($(this).offset().top - scrollTop) <= 100){
                $(this).toggleClass("fade-in");
             }
        })
    }