Transforming elements on scroll
The amount of applied transformation depends on the visibility of the element in the viewport
HTML
<div id="output"></div>
<p>
Scroll down...
</p>
<div class="parallaxBox" id="firstBox"></div>
<div class="parallaxBox" id="secondBox"></div>
<div class="parallaxBox" id="thirdBox"></div>
CSS
#output {
right: 0;
position: fixed;
padding: 5px;
background: yellow;
}
.parallaxBox {
width: 100px;
height: 250px;
margin: 400px auto;
}
#firstBox {
background: red;
}
#secondBox {
background: blue;
}
#thirdBox {
background: green;
}
JavaScript
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) {
element.style.transform = "skew(" + String((1.0 - percentage(element)) * 50) + "deg)";
element.style.opacity = percentage(element);
}
document.body.onscroll = function() {
var output = document.getElementById("output");
output.innerHTML = "";
var elements = document.getElementsByClassName("parallaxBox");
for(var i = 0; i < elements.length; i++)
{
output.innerHTML += String(percentage(elements.item(i)))+" ";
parallax(elements.item(i));
}
}