I have multiple divs in my page. This div contains size and color. When scroll down, div visible to the screen should move up and when scroll up, it should return to its original position.
This is the code so far I have tried. With this code, when I scroll down, div is moving up but when I scroll up , div is not coming down. Can anybody please help me?
function isElementInViewport(el) {
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0 &&
rect.bottom >= 0) ||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight)) ||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
window.addEventListener('scroll', function(e) {
winScrollTop = $(this).scrollTop();
var elementsToShow = document.querySelectorAll('.rectangle');
Array.prototype.forEach.call(elementsToShow, function(element) {
if (isElementInViewport(element)) {
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
});
.rectangle {
background-color: red;
height: 444px;
width: 100px;
/* margin-top: -98px; */
z-index: -30;
transition: 0.5s;
transform: translateY(-98px);
margin-bottom: 25px;
}
.is-visible {
transform: translateY(-250px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rectangle"></div>
<div class="rectangle"></div>
<div class="rectangle"></div>
<div class="rectangle"></div>