I'm able to set a nav div to be fixed when scrolled past it, however I need to extend the jQuery code to add a CSS element to the body to push it down by the height of the div to compensate for the jump that happens when the div is made to be fixed.
The jQuery code I'm using is
var $window = $(window),
$stickyEl = $('nav#main'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
I need to add a margin-top of 40px to the body tag when the .sticky class is applied.
Is there a CSS rule I can make that sets margin-top:40px to body, but when .sticky is shown? Something like the opposite of child css elements (>) ?
Specificity relationships only work one way, so there aren't selectors to target parents of elements, and although there are a few ways to do so, I don't think they fully apply to your situation.
I think what you might want to do here is not use toggleClass and just do the check manually, this way you can expand your "callback".
$window.scroll(function() {
if($window.scrollTop() > elTop) {
$stickyEl.addClass('sticky');
$(body).css("marginTop", "40px");
} else {
$stickyEl.removeClass('sticky');
}
});
Or you could just have a hidden div to be the spacer and just use a class to show/hide it, then do something like:
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
$myHiddenDiv.toggleClass('show', $window.scrollTop() > elTop);
});
The other option you could try to do is mess around with the :before selector and create a div that would act as a spacer.