Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make animation happen when a section is in view using javascript

I am still learning web designing and I wanted to start an animation on a div which is in middle of the page. I searched for it but everywhere I found it using j-query. Is there any way it can be done using pure CSS and JavaScript.

<div>A lot of contents which take whole screen</div>
<div>Section where animation has to happen when come into view</div>

Please help if it can be done using javascript only and if not then what is the easiest way of doing it.

like image 228
Siddharth Soni Avatar asked Oct 12 '25 18:10

Siddharth Soni


1 Answers

This answer does exactly the same as the other answer, but it uses IntersectionObserver

  • Thus "No need to enter JS on every scroll." - A Haworth's comment

This Code is referred from here

  • also i have used Tschallacka's edit to remove copy paste (using .repeat(500) in js)

var elements;
var windowHeight;
document.getElementById('content').innerText = "A lot of content to fill up the page. ".repeat(500)

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    const square = entry.target.querySelector('.noanimfornow');

    if (entry.isIntersecting) {
      square.classList.add('animateme');
      return; // if we added the class, exit the function
    }

    // We're not intersecting, so remove the class!
    square.classList.remove('animateme');
  });
});

observer.observe(document.querySelector('.animwrapper'));
@keyframes myanim {
  from {
    opacity: 0;
    transform: scale(.7, .7)
  }
  to {
    opacity: 1;
  }
}

.animateme {
  animation: myanim 5s;
}

.noanimfornow {
  opacity: 0;
}
<div id="content"></div>
<div class="animwrapper">
  <div class="noanimfornow">Section where animation has to happen when come into view</div>
</div>
like image 135
Neptotech -vishnu Avatar answered Oct 14 '25 11:10

Neptotech -vishnu