I’m trying to make two images appear in a "front-image" section when I scroll. When the user scrolls down, the images should behave as follows:
- top-image: must go down
- bottom-image: must go up
when the user scrolls up the behavior must be reversed.
What I’ve tried so far using a pinch of js to follow the scroll:
const frontImageSection = document.querySelector('.front-image');
const topImage = document.querySelector('.top-image');
const bottomImage = document.querySelector('.bottom-image');
window.addEventListener('scroll', () => {
const scrollPosition = window.scrollY;
const windowHeight = window.innerHeight;
const frontImageSectionTop = frontImageSection.offsetTop;
const frontImageSectionHeight = frontImageSection.offsetHeight;
const topImageOffset = (scrollPosition / frontImageSectionHeight) * 100;
let bottomImageOffset = -((scrollPosition / frontImageSectionHeight) * 100);
topImage.style.transform = `translateY(${topImageOffset}%)`;
bottomImage.style.transform = `translateY(${bottomImageOffset}%)`;
});
body {
height: 300vh;
}
.front-image {
top: 20%;
position: relative;
padding-top: 96.2px;
overflow: hidden;
}
.front-image .top-image,
.front-image .bottom-image {
position: fixed;
transition: transform 0.3s ease-in-out;
width: 200px;
}
.front-image .top-image {
top: 0;
right: 10%;
}
.front-image .bottom-image {
bottom: 0;
left: 10%;
}
.front-image .content picture img {
width: 100%;
height: 525px;
object-fit: cover;
}
<body>
<section class="front-image">
<div class="square-box"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 px-0">
<div class="content">
<picture>
<img src="https://i.imgur.com/bTX82bl.jpeg" class="">
</picture>
</div>
</div>
</div>
</div>
<img src="https://i.ibb.co/Vvy6Cfp/Pngtree-isolated-cat-on-white-background-9158356.png" alt="Logo"
class="top-image">
<img src="https://i.ibb.co/Vvy6Cfp/Pngtree-isolated-cat-on-white-background-9158356.png" alt="Logo"
class="bottom-image">
</section>
</body>
but the behavior is quite bizarre and doesn’t even seem smooth, also, the images should appear within the section, but for some reason they pop out I can’t figure out where I’m going wrong, could anyone help me?
Thanks in advance
2
Answers
You can change cat’s position to absolute instead of fixed. Also set your transition as linear (not ease-in-out) and scroll-behavior: smooth; in .top-image and bottom-image. Also remove the padding from your .front-image and you won’t have that ‘overflowing cat’ as offsetHeight takes into account padding.
You can check this. Now cats don’t show when scrollposition is 0