Many times I've encountered a design in which there is a fixed navigation bar. With a known height or some simple JS this is an easy thing to accomplish; however, if you use the toolbar from core or Admin Toolbar module then you've likely encountered the issue with overlap.
The problem is the toolbar adds padding to the body, not only on resize, but also depending on what you click in the menu. For example, clicking on "Manage" can hide the second row, changing the body padding and throwing your fixed nav out of whack.
Since there is no real easy "event" here short of digging into the toolbar selectors, I've solved this by using a MutationObserver. Here's how:
First, we want to set the configuration:
javascript
var config = {
attributes: true
attributeFilter: ["style"]
}
By default, pretty much every option is set to `false` (see here for more info on the available options), so we are going to say we care about attributes and specifically filter only the style attribute.
Now we setup what the observer will do:
javascript
// Observe body padding-top from admin toolbar.
var observer = new MutationObserver(function (mutations) {
var header = document.getElementsByTagName('header')[0];
header.style.marginTop = mutations[0].target.style.paddingTop || 0;
});
SAWEEET! Now when the style attribute is changed, we set it to the margin-top of our <header> element.
Now tell it what to observe:
javascript
// Doc Ready.
document.addEventListener("DOMContentLoaded", function() {
// Observe the body for style changes.
observer.observe(document.getElementsByTagName("BODY")[0], config);
});
That's it that's all. Now your fixed header will adjust when body padding changes. Combine this with a library that only loads when a user has the "access toolbar" permission and you're laughin'.
I was going to add a piece here about how to do the fixed nav in the first place, but I figure if you're here you know that. Leave a comment if you'd like to see the full working code.