JSFiddle - React, Tailwind, and code Playground
by Hari Menon
HTML
<div class="content">
<div class="text">Hello World</div>
</div>
CSS
body {
height: 1400px;
}
.content {
margin-top: 700px;
position: relative;
height: 200px;
background: blue;
}
JavaScript
$(document).ready(function() {
setParalaxContent();
$(window).scroll(function() {
setParalaxContent();
});
});
window.p = {};
function setParalaxContent() {
p = {
scrollTop: $(window).scrollTop(),
documentHeight: $(document).height(),
windowHeight: $(window).height(),
contentTop: $('.content').position().top,
contentHeight: $('.content').height()
};
if (p.windowHeight / 2 + p.scrollTop < p.contentHeight / 2 + p.contentTop) {
p.percent = (p.windowHeight / 2 + p.scrollTop) / (p.contentHeight / 2 + p.contentTop);
}
else if (p.windowHeight / 2 + p.scrollTop > p.contentHeight / 2 + p.contentTop) {
p.percent = (p.windowHeight / 2 + p.scrollTop) / (p.contentHeight / 2 + p.documentHeight - p.contentHeight - p.contentTop);
}
else p.percent = 1;
$('.content .text').text(p.percent);
$('.content').animate({
opacity: 1 - Math.abs(p.percent - 1)
}, 1);
}