JSFiddle - React, Tailwind, and code Playground
HTML
<div id="block"></div>
<div id="block1" class="scroll"></div>
<div id="block2"></div>
CSS
#block {width: 100%; height: 2000px; background: #000;}
#block1 {width: 100%; height: 200px; background: red; opacity: 0;}
#block1.animated {
opacity: 1;
-webkit-transition: opacity 1s ease;
-o-transition: opacity 1s ease;
-ms-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;
transition: opacity 1s ease;
}
#block2 {width: 100%; height: 2000px; background: #000;}
JavaScript
$(".scroll").each(function() {
var block = $(this);
$(window).scroll(function() {
var top = block.offset().top;
var bottom = block.height()+top;
top = top - $(window).height();
var scroll_top = $(this).scrollTop();
var block_center = block.offset().top + (block.height() / 2);
var screen_center = scroll_top + ($(window).height() / 2);
if(block.height() < $(window).height()) {
if ((scroll_top > (top-(block.height()/2))) && ((scroll_top < bottom+(block.height()/2))) && (scroll_top + $(window).height() > (bottom-(block.height()/2))) && (scroll_top < (block.offset().top+(block.height()/2)))) {
if (!block.hasClass("animated")) {
block.addClass("animated");
}
} else {
if((block.offset().top + block.height() < scroll_top) || (block.offset().top > (scroll_top + $(window).height()))) {
block.removeClass("animated");
}
}
} else {
if ((scroll_top > top) && (scroll_top < bottom) && (Math.abs(screen_center - block_center) < (block.height() / 4))) {
if (!block.hasClass("animated")) {
block.addClass("animated");
}
} else {
if((block.offset().top + block.height() < scroll_top) || (block.offset().top > (scroll_top + $(window).height()))) {
block.removeClass("animated");
}
}
}
});
});