If you notice that your website is a little bit boring then maybe a little animation might help to make certain elements do a little fading or animation as it comes visible in the viewport.
The snippet below is a good way to detect of when is the element visible in the viewport. To complete the animation you need to work with the CSS transition or opacity for fading effects.
Thanks for the person who contributed this function in @stackflow.com
function isElementInViewport(el) {
// special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0
&& rect.bottom >= 0)
||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight))
||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
To make use of this function then here is a very simple example.
// this will return an array of elements that has a class .animate-me
var elementsToVisible = document.querySelectorAll('.animate-me');
//loop the array
elementsToVisible.forEach(function (element) {
if (isElementInViewport(element)) {
element.classList.add('visible');
} else {
element.classList.remove('visible');
}
});
In your CSS you have to specify the animation effects.
.animate-me {
opacity: 0;
transition: transform 4s .25s cubic-bezier(0,1,.3,1),
opacity .3s .25s ease-out;
}
.animate-me.visible {
opacity: 1;
-webkit-transform: rotateZ(-2deg);
transform: rotateZ(-2deg);
}