Lloyd aaron Lloyd aaron - 5 months ago 27
Javascript Question

Do something on Scroll

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;
}
}
}

Answer

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>

Comments