Having a sticky sidebar on desktop presents a challenge when trying to "unstick" it before it overlaps with the footer. The height of the sidebar is dynamic, so its stop position changes as different elements are opened or closed.
The main question at hand is how to add:
css('top', dynamic-value);
to an EXISTING class in order to temporarily "unstick" the sidebar once it reaches the footer, and then resume normal sticky navigation by removing this specific class containing the dynamic top value.
Attempting to add the CSS using the following code snippet results in the styles being added directly to the DOM instead of applying them to the specified class:
element.addClass('not-sticky')
$('.not-sticky').css('top',dynamic-value);
Consequently, upon removing the class, the added CSS remains in the DOM causing disruptions. Is there a way to add CSS to an existing class without affecting the DOM structure? Alternatively, is there a method to remove dynamically added CSS from the DOM?
//css
@include respond-to(desktop) {
width: 310px;
float: left;
&.fixed {
top: 20px;
height: auto;
position: fixed;
}
&.not-fixed {
//top: 5656px;
position: absolute;
}
}
//jquery
$(document).scroll(function() {
scrollTop = $(document).scrollTop();
sidebar = $(".sidebar");
sidebarFixed = sidebar.hasClass("fixed");
sidebarHeight = sidebar.height();
var footerTop = $('.footer').offset().top; // where footer starts
// FIXED desktop navigation conditions
var stickyDesktop = scrollTop > (sidebarOffset - 20);
// STOP being sticky navigation condition
// when the sidebar has scrolled far enough from the top of the document (scrollTop)
// that the bottom of the sidebar (sidebar Height) hits the top of the footer (footerTop)
// the 120 is to account for spacing between the top of the footer and bottom of sidebar
var stickyLimit = (scrollTop + sidebarHeight + 120) > footerTop;
// this is to be the top: diff for the .not-fixed class
var diff = scrollTop - stickyLimit;
if(windowWidth >= 1080) {
// on desktop make sidebar sticky on scroll
stickyDesktop = scrollTop > (sidebarOffset - 20);
sidebar.toggleClass('fixed',stickyDesktop);
// if the navigation is sticky
if(sidebarFixed === true) {
pageIntro.slideUp(300);
} else {
pageIntro.slideDown(300);
}
// if condition to stop fixed navigation is met
if (stickyLimit === true) {
stickyLimit = (scrollTop + sidebarHeight + 120) > footerTop;
// stop nav being sticky
sidebar.addClass('not-fixed');
// THIS CSS DOESN'T GET ADDED TO THE CLASS BUT TO THE DOM
$(".not-fixed").css('top',diff);
} else {
// regular sticky again
sidebar.removeClass('not-fixed');
}
}
}); // end document scroll function