JSFiddle - React, Tailwind, and code Playground
HTML
<div class="header-nav__dropdown">
<li><a href="#first">first</a></li>
<li><a href="#second">second</a></li>
<li><a href="#third">third</a></li>
</div>
<main>
<section><a name="first"></a></section>
<section><a name="second"></a></section>
<section><a id="third"></a></section>
</main>
SCSS
section {
height: 500px;
background: #eee;
&:first-child {
background: #dfd;
}
&:last-child {
background: #ddf;
}
}
JavaScript
$(() => {
const scrollTo = (target, duration = 800) => {
if (!target) {
return;
}
const delta = $(window).width() < 768 ? 0 : $('.header-nav').outerHeight();
$('html,body').animate({
scrollTop: $([target, `a[name="${target.replace(/^#+/g, '')}"]`].join(', ')).first().offset().top - delta
}, duration);
};
if (location.hash) {
scrollTo(location.hash);
}
$(document).on('click', '.header-nav__dropdown li a', function(e) {
const $this = $(this);
const hash = (this.href || '').split('#').pop();
if ($this.closest('.header-nav__list > ul > li').hasClass('isActive') || !hash) {
return;
}
e.preventDefault();
scrollTo('#' + hash);
$this.closest('.header-nav__dropdown').hide({
duration: 100,
complete: function() {
this.removeAttribute('style');
}
});
});
});