JSFiddle - React, Tailwind, and code Playground
by mrjordy
HTML
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
<p id="first">
First
</p>
<p id="second">
Second
</p>
<p id="third">
Third
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
CSS
p {
margin: 600px 0;
}
JavaScript
// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// Captures click events of all a elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);