Webdesign, WordPress

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.

        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

        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

Now you can simply create a corresponding animation in CSS like this:

  	opacity: 0.4;
	transition: all 1s;

  	opacity: 1;

Now the elements fade in when scrolling in and out when scrolling out.