I’m trying to create a sticky aside element that stays on top of other items within the same container when scrolling. However, I’m facing some issues with the implementation.
The code below attempts to create a sticky aside element that should stay on top of other items in the container when scrolling. However, the aside element either doesn’t stick or overlaps with other items.
I want the sticky aside element to stick at the top of the container and scroll with the page until it reaches the end of the container, where it should stop scrolling. It should not overlap with other items within the container.
Here’s the code I’ve tried:
window.addEventListener('scroll', function() {
var stickyAside = document.getElementById('sticky-aside');
var container = stickyAside.closest('.container');
var containerTop = container.offsetTop;
var containerBottom = containerTop + container.offsetHeight;
var asideHeight = stickyAside.offsetHeight;
if (window.pageYOffset > containerBottom - asideHeight) {
stickyAside.classList.add('sticky');
} else {
stickyAside.classList.remove('sticky');
}
});
#sticky-aside {
width: 100%;
top: 0;
}
.row {
position: relative;
}
.sticky {
position: fixed;
width: 100%;
top: 0;
}
<div class="container mt-5">
<div class="row">
<!-- My posts section -->
</div>
</div>
<div class="container mt-5">
<div class="row mt-5 border-top border-dark pt-5">
<aside class="col-sm-4" id="sticky-aside">
<!-- Sticky aside content -->
</aside>
</div>
</div>
2
Answers
Try this:
JS(it checks if the window’s scroll position is within the container’s bounds, excluding the height of the sticky aside element):
CSS(to position the sticky aside element at the top without specifying a fixed height):
I might be misunderstanding the question, but I believe this can all be done sans JavaScript using
position: sticky;
.A few things worth noting:
overflow
value settop: 0;
)Hopefully the following code will help: