I am trying to get an element in a left sidebar to stay in view when a user scrolls down the page.
Here is an example of a page where I am trying to get this to work: https://guitar-dreams.com/guitar-lesson/triad-arpeggios-2-strings/20
At first I was trying Bootstrap Affix, but it was glitchy. I had created a question here:
Unexpected behavior of JS Affix - how to force div column to stay fixed width?
but decided to just give up on Bootstrap Affix. So I read more and came across this solution:
I used this approach and got things working almost how I need.
But when you scroll down, the sidebar element can touch the footer. When that happens and you start to scroll up, the whole functionality breaks down and the sidebar will not move back upwards.
Most solutions seem to use an approach where you add/remove a class to control position as fixed or not. I like the approach from the above link, with its animation approach, but just not sure how to alter the animation behavior so that footer is not touched.
Here is the code written by user benvc in the above link:
$(function() {
const sidebar = $('#sidebar-container');
const widget = $('#leftsidebar');
const footer = $('#footer');
const space = 1; // arbitrary value to create space between the window and widget
const startTop = sidebar.offset().top + 1; // arbitrary start top position
const endTop = footer.offset().top - widget.height() - space;
widget.css('top', startTop);
$(window).scroll(function() {
let windowTop = $(this).scrollTop();
let widgetTop = widget.offset().top;
let newTop = startTop;
if (widgetTop >= startTop && widgetTop <= endTop) {
if (windowTop > startTop - space && windowTop < endTop - space) {
newTop = windowTop + space;
} else if (windowTop > endTop - space) {
newTop = endTop;
}
widget.stop().animate({
'top': newTop
});
}
});
});
Ideal result would be a sidebar element that stays in view during scrolling and which is not allowed to touch the footer. This should work equally well in chrome, safari, firefox.
If you go to the link I placed at the very top, which shows how this is currently working (almost) on my site, you can see the rest of the code, that is, the HTML and CSS. I made some adjustments to the CSS and JS (for instance changing value of const space
) compared to the original solution, and maybe some of those changes are coming into play here. In chrome, seems to be pretty much working ok, but in safari seems that once the sidebar element comes near the footer the whole functionality stops and the element doesn't move back upwards when scrolling towards top.
Any ideas on how to get this working a little better?
Thanks, Brian