I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up.
I've created a script that calculates the window height, current scroll position (scrollY), and the point where the sidebar should 'stop'. I control the stopping point by adjusting the css 'bottom' property. However, I am encountering two issues with this method:
- When the sidebar is close to the 'pagination' where it should stop, it suddenly jumps down as I scroll up, and vice versa.
- As I scroll the page, the sidebar moves continuously instead of staying in place
Below is the code I am using. HTML:
<div class="container">
<aside></aside>
<div class="content">
<div class="pagination"></div>
</div>
<footer></footer>
</div>
CSS:
aside {
display: flex;
position: fixed;
background-color: #fff;
border-radius: 4px;
transition: 0s;
transition: margin .2s, bottom .05s;
background: orange;
height: 350px;
width: 200px;
}
.content {
display: flex;
align-items: flex-end;
height: 1000px;
width: 100%;
background: green;
}
.pagination {
height: 100px;
width: 100%;
background: blue;
}
footer {
height: 500px;
width: 100%;
background: red;
}
JS:
let board = $('.pagination')[0].offsetTop;
let filterPanel = $('aside');
if (board <= window.innerHeight) {
filterPanel.css('position', 'static');
filterPanel.css('padding-right', '0');
}
$(document).on('scroll', function () {
let filterPanelBottom = filterPanel.offset().top + filterPanel.outerHeight(true);
let bottomDiff = board - filterPanelBottom;
if(filterPanel.css('position') != 'static') {
if (window.scrollY + window.innerHeight - (bottomDiff*2.6) >= board)
filterPanel.css('bottom', window.scrollY + window.innerHeight - board);
else
filterPanel.css('bottom', '');
}
});
Check out the live demo on Codepen here
The sidebar is denoted by an orange background, while the block indicating its stopping point is highlighted in blue. Thank you in advance for any assistance provided.