JSFiddle - React, Tailwind, and code Playground
HTML
<ul class="right">
<li class="right"><a href="#contact">Contact</a></li>
<li class="right"><a href="#home"> home </a></li>
</ul>
<div class="home-wrap page" id="home">
Home
</div>
<div class="contact-wrap page" id="contact">
Contact
</div>
CSS
div.home-wrap {
height: 1000px;
}
div.contact-wrap {
height: 1000px;
}
JavaScript
$(document).ready(function() {
$('a[href^="#"]').on("click", function() {
var target = $(this.hash);
var hash = this.hash;
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({
scrollTop: target.offset().top
}, 500, function() {
location.hash = hash;
});
return false;
});
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
};
var $document = $(document),
$window = $(window),
$pages = $(".page"),
oldHash = location.hash;
var changeHashOnScroll = debounce(function() {
var scrollTop = $document.scrollTop(),
newHash = "";
$.each($pages, function(key, value) {
var $this = $(value);
if ($this.offset().top < (scrollTop + $window.height() / 2)) {
newHash = $this.attr("id");
}
});
if (newHash !== undefined && newHash !== "" && newHash !== oldHash) {
var fx, node = $('#' + newHash);
if (node.length) {
node.attr('id', '');
fx = $('<div></div>')
.css({
position: 'absolute',
visibility: 'hidden',
top: $(document).scrollTop() + 'px'
})
.attr('id', newHash)
.appendTo(document.body);
}
location.hash = newHash;
console.log(newHash);
if (node.length) {
fx.remove();
node.attr('id', newHash);
}
oldHash = newHash;
}
}, 250);
$document.on("scroll", changeHashOnScroll);
});