I wrote a piece of code with jQuery to start a fade-in animation on some content I have on my new portfolio website. The code works and the animation appears. Just the moment the animation starts is unlogic. In my mobile version, the animation starts when I’m halfway in the p
text.
Any options to manipulate this within this code to select a certain amount of pixels from the innerHeight
before the animation starts? Let’s say when the objectTop
reaches windowMiddle
? Comments are much appreciated.
$(window).on("load", function() {
$(window).scroll(function() {
var windowBottom = $(this).scrollTop() + $(this).innerHeight();
$(".fade").each(function() {
var objectBottom = $(this).offset().top + $(this).outerHeight();
if (objectBottom < windowBottom) { //object shows on scroll
if ($(this).css("opacity") == 0) {
$(this).fadeTo(500, 1);
}
// } else {
// object fade away scrolling up
// if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);
// }
}
});
}).scroll();
});
.fade {opacity: 1; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p> Bladibladibla </p>
</div>