JSFiddle - React, Tailwind, and code Playground
HTML
<div class="menu" style="height:70px;">
<a href="#div1">go to one</a>
<a href="#div2">go to two</a>
<a href="#div3">go to tree</a>
</div>
<div style="clear:both;height: 500px;background-color: red;">
<h1>
Top Page
</h1>
</div>
<div id="div1" style="height: 500px;background-color: green;">
First Anchor
</div>
<div id="div2" style="height: 500px;background-color: white;">
Second Anchor
</div>
<div id="div3" style="height: 500px;background-color: yellow;">
Third Anchor
</div>
CSS
.menu {
width: 100%;
display: block;
background-color: #c4c4c4;
opacity: 0.5;
position: fixed;
}
h1 {
position: absolute;
top: 50%;
left: 40%;
}
a {
margin: 15px;
padding: 15px;
border: 1px solid #000;
background-color: #FFF;
opacity: 0.8;
}
JavaScript
var $ = jQuery.noConflict();
$(document).ready(function($) {
var menu_height = $('.menu').height();
(function(document, history, location) {
var HISTORY_SUPPORT = !!(history && history.pushState);
var anchorScrolls = {
ANCHOR_REGEX: /^#[^ ]+$/,
OFFSET_HEIGHT_PX: menu_height,
/**
* Establish events, and fix initial scroll position if a hash is provided.
*/
init: function() {
this.scrollIfAnchor(location.hash);
$('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
},
/**
* Return the offset amount to deduct from the normal scroll position.
* Modify as appropriate to allow for dynamic calculations
*/
getFixedOffset: function() {
return this.OFFSET_HEIGHT_PX;
},
/**
* If the provided href is an anchor which resolves to an element on the
* page, scroll to it.
* @param {String} href
* @return {Boolean} - Was the href an anchor.
*/
scrollIfAnchor: function(href, pushToHistory) {
var match, anchorOffset;
if(!this.ANCHOR_REGEX.test(href)) {
return false;
}
match = document.getElementById(href.slice(1));
if(match) {
anchorOffset = $(match).offset().top - this.getFixedOffset();
$('html, body').animate({ scrollTop: anchorOffset});
// Add the state to history as-per normal anchor links
if(HISTORY_SUPPORT && pushToHistory) {
history.pushState({}, document.title, location.pathname + href);
}
}
return !!match;
},
/**
* If the click event's target was an anchor, fix the scroll position.
*/
delegateAnchors: function(e) {
var elem = e.target;
if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
e.preventDefault();
}
}
};
$(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);
});