Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Animation on scroll (only animate once)

So I have an "active" tag that is set to be added to elements with the class "reveal" when they are in the viewport. But after I scroll down the class "active" is now removed. How do I make it so that when "active" is first applied it does not get removed again. Below is the JavaScript that adds the "active" class.

function reveal() {
  var reveals = document.querySelectorAll(".reveal");

  for (var i = 0; i < reveals.length; i++) {
    var windowHeight = window.innerHeight;
    var elementTop = reveals[i].getBoundingClientRect().top;
    var elementVisible = 20;

    if (elementTop < windowHeight - elementVisible) {
      reveals[i].classList.add("active");
    } 
    else {
      reveals[i].classList.remove("active");
    }

  }
}

window.addEventListener("scroll", reveal);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Welcome to StackOverflow.
You are using if else condition which is not required here. Just using a if block inside loop will do the work. Please see below code:

function reveal() {
  var reveals = document.querySelectorAll(".reveal");

  for (var i = 0; i < reveals.length; i++) {
    var windowHeight = window.innerHeight;
    var elementTop = reveals[i].getBoundingClientRect().top;
    var elementVisible = 20;

    if (elementTop < windowHeight - elementVisible) {
      reveals[i].classList.add("active");
    }
    /*
    Not needed
    else {
      reveals[i].classList.remove("active");
    }
    */

  }
}

window.addEventListener("scroll", reveal);

I have commented else block so it is not executed. Thanks!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading