Reputation: 105
How to do to apply the fade, compared with their height, on each
element and not the whole ?
HTML :
<div class="test fade"></div>
CSS :
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font: 1em 'Open Sans', sans-serif;
}
.test {
height: 70vh;
width: 30%;
background-color: rgba(0, 0, 0, 0.6);
margin: 1em auto;
}
JS :
var $elem = $('.test.fade');
for (var i = 0; i <= 5; i++) {
$elem.clone().appendTo('body');
}
$(window).scroll(function() {
var percent = $(this).scrollTop() / ($(document).height() - $(this).height());
$('.fade').each(function() {
$(this).css('opacity', 1 - percent);
});
});
Upvotes: 0
Views: 53
Reputation: 135802
I suggest using Element.getBoundingClientRect()
to calculate the position of the element relative to the viewport.
With its position relative to the viewport, you can calculate how much % of it is outside the viewport and use that as opacity
(after conversion to a 0-1 value):
var $elem = $('.test.fade');
for (var i = 0; i <= 5; i++) {
$elem.clone().appendTo('body');
}
$(window).scroll(function() {
$('.fade').each(function() {
var bounds = this.getBoundingClientRect();
var op = Math.max((bounds.height + Math.min(bounds.top, 0)) / bounds.height, 0);
$(this).css('opacity', op);
});
});
Upvotes: 1