I had a real game getting this to work! – Essentially, I wanted to trigger a CSS animation when the viewer gets to a certain part of the page via scrolling, or when a visitor is viewing a specific section of a WordPress page. By default, CSS animations will usually trigger when a page loads, you can set delays before an animation is triggered but generally, it’s on page load they fire off. After a lot of searching on Google and asking nice people on various forums, I came across this solution. This particular method uses JavaScript and the IntersectionObserver to detect whether a section of the site is visible in the viewport. If the section of the site is in the viewport, it then changes the CSS code so that it fires off the animation.
In the code below the IntersectionObserver is looking for anywhere in the page that has the CSS class ‘onScroll’ if it’s also in the viewport it will add the class – ‘animateThis’ which triggers the animation. This first JavaScript triggers the animation once when it comes into view and ignores the animated elements as you scroll back up the page.
<script>
document.addEventListener("DOMContentLoaded", function() {
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animateThis');
// Stop observing so it never triggers again
observer.unobserve(entry.target);
}
});
});
const squares = document.querySelectorAll('.onScroll');
squares.forEach(element => observer.observe(element));
});
</script>
This second JavaScript triggers the animation each time it comes into view, this might be good if you want to keep things moving!
<script>
document.addEventListener("DOMContentLoaded", function() {
// Create the observer like the examples above
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animateThis');
return;
}
entry.target.classList.remove('animateThis');
});
});
// Get multiple elements instead of a single one using "querySelectorAll"
const squares = document.querySelectorAll('.onScroll');
// Loop over the elements and add each one to the observer
squares.forEach((element) => observer.observe(element));
})
</script>
The code above includes a wrapper so that it waits until DOMContentLoaded (or when the appropriate code has loaded) before it triggers the JavaScript. I’ve added the wrapper below. Thanks again to the guys at StackOverflow for their help with this. I placed the JavaScript into the main body block using WPCode / Code Snippets plugin.
document.addEventListener("DOMContentLoaded", function() {
Your Code Here!
})
I don’t 100% know how this all works but it does!











