When is an element in the viewport
There is a relatively new way to easily see if an element is in the viewport (visible area) or not. It is a so called vanilla script, so it is pure JavaScript and does not need any external library.
<script> document.querySelectorAll('.meinElement').forEach((i) => { if (i) { const observer = new IntersectionObserver((entries) => { observerCallback(entries, observer, i) }, {threshold: 1}); // How much of the element is in the visible area observer.observe(i); } }) const observerCallback = (entries) => { entries.forEach((entry, i) => { if (entry.isIntersecting) { entry.target.classList.add('show'); // add a class } else { entry.target.classList.remove('show'); // remove class when outside the view } }); }; </script>
Now you can simply create a corresponding animation in CSS like this:
.myDiv{ opacity: 0.4; transition: all 1s; } .myDiv.show{ opacity: 1; }
Now the elements fade in when scrolling in and out when scrolling out.