Hey there! I've been trying to figure out if it's possible to create a sticky sidebar within a specific div container. I attempted using position: fixed, but this caused the element to adjust relative to the window rather than its parent container. After some research, it seems like most responses indicate that achieving a fixed position relative to the parent div is not possible.
I haven't had much luck finding an alternative solution through my searches (maybe I'm just not great at it). So, I'm turning to you all for help - do you have any idea how I could make a sidebar stick to its parent div instead of the window?
Thanks in advance!
Edit: check out the code on JSFiddle
jQuery(function() { // document ready
var sideBarTop = $('#sidebar').offset().top; // position top
var sideBarLeft = $('#sidebar').offset().left //position left
jQuery(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns scroll from top
if(sideBarTop < windowTop) {
$('#sidebar').css({position: 'fixed', top: 0, left: sideBarLeft});
}
else {
$('#sidebar').css('position', 'static');
}
});
});