I want to give the sidebar_wrapper a position of fixed when the page scrolls to its (sidebar) bottom content while the left-side continues to scroll independently because the left-side has more content than the sidebar div. I am using Tailwindcss.
I am struggling to make the code work.
The code has two issue
- when the scroll starts, the sidebar_wrapper div overflows the sidebar and does not add the fixed class to it then it reaches the end of the sidebar content.
- when scrolling back down, the sidebar_wrapper div remains fixed on the top position.
I want it to reverse the operation.
here is the code
<div class="grid grid-cols-1 md:grid-cols-[2fr_1fr] ">
<div class="left-side">
content .....
<div>
<div class="sidebar>
<div="class="sidebar_wrapper">
content....
</div>
</div>
</div>
<script>
let sidebar = document.getElementsByClassName("sidebar")[0];
let sidebar_wrapper= document.getElementsByClassName("sidebar_wrapper")[0];
window.onscroll = () => {
let scrollTop = window.scrollY;
let viewportHeight = window.innerHeight;
let sidebarTop = sidebar.getBoundingClientRect().top + window.pageYOffset;
let contentHeight = sidebar_wrapper.getBoundingClientRect().height;
if( scrollTop >= contentHeight - viewportHeight + sidebarTop) {
sidebar_wrapper.style.transform = `translateY(-${(contentHeight - viewportHeight + sidebarTop)}px)`;
sidebar_wrapper.style.position = "fixed";
}
else {
sidebar_wrapperstyle.transform = "";
sidebar_wrapperstyle.position = "";
}
};
</script>