Element Animation Based on Visibility When Scrolling (Parallax Effect)
Ever wanted to make some cool animations on your website? Maybe you will find this quick and simple trick a bit helpful. What about animating the divs or other elements when scrolling the page so the animation is relative to the visibility of the object on the page? This way one can create some cool effects such as parallax or simple image popping out or fading in when scrolling the page. So here we go using JavaScript and CSS:
function percentage(element) { var rect = element.getBoundingClientRect(); var topOffset = window.innerHeight - rect.top; var bottomOffset = window.innerHeight - rect.bottom; if (topOffset > 0 && bottomOffset < 0) return topOffset / rect.height; else if (bottomOffset > 0) return 1.0; else return 0.0; } function parallax(element) { var amount = percentage(element); element.style.transform = "skew(" + String((1.0 - amount) * 50) + "deg)"; element.style.opacity = amount; } document.body.onscroll = function() { var elements = document.getElementsByClassName("parallaxBox"); for(var i = 0; i < elements.length; i++) parallax(elements.item(i)); }
So what does this code do? The function percentage simply calculates how much of the element is visible on the screen (in the viewport). It’s zero when it’s still somewhere down and one has to scroll to get there and it’s one when it’s already on the screen (or hidden at the top aka the reader has already seen it when scrolling the page). The logic is simple, we just compare the position coordinates of the element with the page size. Note that this function works only for vertical movement and doesn’t care about the element hiding at the top side of the page. It can be however extended quite simply following the same logic. And since we have this 0-1 output we can animate any property in the parallax function. Here is link to an interactive fiddle. You can use this code however you need to.
Published:Keywords: javascript,programming,html,css,website,web design
#htmltricks #htmltutorial #csstutorial #csstricks #javascripttutorial #javascripttricks
Privacy Terms