Reputation: 3523
I have a webpage which has a floating top navigational bar. I want to add anchor links to a table of contents to quickly direct to other places on the page.
#top {
display: flex;
z-index: 100;
background-color: rgba(20, 20, 20, 0.75);
position: fixed;
top: 0px;
margin-left: auto;
margin-right: auto;
left: 0px;
right: 0px;
height: 75px;
}
#bottom {
padding-top: 75px;
}
<div id="top">
</div>
<div id="bottom">
<a href='#example'>Click Here</a>
<br/>
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> a
<br/> <a id='example'></a> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
<br/> b
</div>
When you click "click here", the outcome I'd like is the first "b" (where the anchor leads to) appears underneath the top floating bar. Instead, when you click "click here", it brings the first "b" to the top of the page, hidden by the floating bar.
How can I have it such when I click the anchor link, it points to the anchor offset by 75px (for example, if the <a>
is 200px from top and I click the anchor link, it'll go to 275px instead of 200px from top)? Is there a no-JS option?
Upvotes: 0
Views: 1131
Reputation: 369
Here you go, this will give you distance - 75px offset
jQuery(document).ready(function() {
jQuery("a").on('click', function(event) {
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
var hash = this.hash;
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top - 75
}, 1200, function() {
window.location.hash = hash;
});
} // End if
});
});
Upvotes: 2