On my site I have a sticky header so when I use anchor links they get covered by the header.
I found a bit of script that solves my problem... the only problem I have found with it is it only works once... if I scroll back to the top and hit the link again the header covers it... If I hit another anchor link on the same page it works and then go back to the previous link it works... it's only when I hit the same link twice.
(function($, window) {
var adjustAnchor = function() {
var $anchor = $(':target'),
fixedElementHeight = 51;
if ($anchor.length > 0) {
window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
}
};
$(window).on('hashchange load', function() {
adjustAnchor();
});
})(jQuery, window);
I found this code on another question and it is the only thing that comes close to what I need. Some other scripts I have tried affect Bootstrap dropdown's which use id's. I would like to use a CSS solution such as...
:target::before {
display: block;
content: " ";
margin-top: -51px;
height: 51px;
visibility: hidden;
}
The only problem with that is it doesn't work if the target has any top padding.
So my question is, is there a way to make the script above kind of reset after it fires so it will work on the same link multiple times (again I found it here offsetting an html anchor to adjust for fixed header? Can you see any potential problems using that scrip? Does anyone have a pure CSS solution that actually works (I've tried everything on this page http://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/)? I manage a large site with content managers so I cannot control if a anchor has margin or padding on the top.. so the solution has to be flexible. Like I said the scrip above is the best solution I have found so far. Thanks!