0

I'm trying to use a fade effect when the page is scrolled, but AddClass() only works on the first div element, when I repeat the same code in the HTML, it doesn't work on the second div, only on the first.

$(window).scroll(function () {
  var cbScroll = $(this).scrollTop();
  if (cbScroll > $(".Top").offset().top - $(window).height() / 1.2) {
    $(".Top").each(function (i) {
      setTimeout(function () {
        $(".Top").eq(i).addClass("fadeUpEffect");
      }, 300 * (i + 1));
    });
  } else {
    $(".Top").removeClass("fadeUpEffect");
  }
});

HTML:

<div class="Top">1</div>
<div class="Top">2</div>
<div class="Top">3</div>

CSS:

.Top {opacity: 0;}

.fadeUpEffect{ 
  animation-name: fadeUpCB;
  -webkit-animation-name: fadeUpCB;
  animation-duration: 0.5s;
  -webkit-animation-duration: 0.5s;
  animation-timing-function: ease-in;
  -webkit-animation-timing-function: ease-in;
  animation-fill-mode: forwards;
  -webkit-animation-fill-mode: forwards;
  visibility: visible !important;;}

@keyframes fadeUpCB{
  0%{transform:translate(0px, 100px); opacity: 0;}
  100%{transform:translate(0px, 0); opacity: 1;}
}

addClass() work on multiple divs

Mahesh Thorat
  • 1
  • 4
  • 11
  • 22

1 Answers1

0

It seems that the problem lies in the way you are using the $('.Top') selector inside the each function. When you repeat the code in the HTML, there are multiple elements with the same class name Top. Therefore, you need to target each element separately instead of targeting all the elements with that class.

You can modify your code as follows to target each element separately:

$(window).scroll(function() {
  var cbScroll = $(this).scrollTop();
  $('.Top').each(function(i, el) {
    if (cbScroll > $(el).offset().top - ($(window).height() / 1.2)) {
      setTimeout(function() {
        $(el).addClass('fadeUpEffect');
      }, 300 * (i+1));
    } else {
      $(el).removeClass('fadeUpEffect');
    }
  });
});

In the above code, we are using the $(el) to target each element inside the each function. This way, the addClass and removeClass functions will work on each element separately.