1

What is the best way if I want to animate an element on scroll? because I noticed that it lags a little bit while scrolling. should I add the class like this?

$(window).scroll(function() {
   if($(this).scrollTop() > 500) {
     $(".element").addClass("animateElement");
   }
}

or make a flag like this one.

animateFlag = true;

$(window).scroll(function() {
   if($(this).scrollTop() > 500) {
     if(animateFlag) {
         $(".element").addClass("animateElement");
         animateFlag = false;
      }
   }
}
Lloyd aaron
  • 282
  • 2
  • 4
  • 10
  • 1
    `addClass` without flag will add class `animateElement` to the element on each scroll you do once you cross your threshold point. Where as via second approach the class will get added only once. – vijayP Jun 27 '16 at 08:31
  • http://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery – Mohammad Kermani May 06 '17 at 12:16

1 Answers1

2

The best way to animate something on scroll is to make the most optimized code. For example, you could use Vanilla JS with a flag like you described and also query for the element before scrolling which would result in something like so:

var animateFlag = true
var element = document.querySelector(".element")

window.addEventListener("scroll", function() {
  if(this.pageYOffset > 0) {
    if(animateFlag) {
      element.classList.add("animateElement");
      animateFlag = false;
    }
  }
})
.element {
  background: yellow;
  width: 200px;
  height: 200px;
  margin-bottom: 1000px;
}

.element.animateElement {
  background: red;
}
<div class="element"></div>