I followed some suggestions on other questions on how to add classes to element when it becomes visible on the screen if you scroll. I keep getting the same results: when I start scrolling the class gets added even though my element is not visible.
function isScrolledIntoView(elem) {
var $window = $(window),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $(elem).offset().top ,
elemBottom = elemTop + $(elem).outerHeight();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).on("scroll", function() {
$('#card1').each(function() {
if (isScrolledIntoView(this)) {
$(this).addClass('cardScroll');
console.log('Class added');
} else {
$(this).removeClass('cardScroll');
}
});
});
"Class added" keeps logging when I start scrolling from the top of the page and my element (#card1) is only in the middle of the page.
HTML:
<div class="col-lg-4 d-flex justify-content-around">
<div class="card" id="card1" style="width: 18rem;">
<div class="rounded-div">
<img class="card-img-top" src="" alt="">
</div>
<div style="text-align: center;" class="card-body">
<h5 class="card-title">Dummy Text</h5>
<p class="card-text">Dummy text</p>
</div>
</div>
</div>
CSS:
.cardScroll {
background-color: #d1e4f3;
box-shadow: 10px 10px 16px 0 rgb(31, 31, 31);
-webkit-transition: box-shadow 0.3s ease-out;
-moz-transition: box-shadow 0.3s ease-out;
-o-transition: box-shadow 0.3s ease-out;
transition: box-shadow 0.3s ease-out;
}