JSFiddle - React, Tailwind, and code Playground
by NOVUSIDEA
HTML
<nav>
<a href="#section-1" class="scroll-to">Section 1</a>
<a href="#section-2" class="scroll-to">Section 2</a>
<a href="#section-3" class="scroll-to">Section 3</a>
<a href="#section-4" class="scroll-to">Section 4</a>
</nav>
<main>
<section id="section-1">Section 1</section>
<section id="section-2">Section 2</section>
<section id="section-3">Section 3</section>
<section id="section-4">Section 4</section>
</main>
SCSS
body {
margin: 0;
}
nav {
position: sticky;
background: rgba(0, 0, 0, 0.5);
text-align: center;
top: 0;
a {
color: #fff;
text-decoration: none;
display: inline-block;
padding: 10px;
}
}
section {
height: 200vh;
border-top: 1px solid #ccc;
text-align: center;
}
JavaScript
$('.scroll-to').on('click', function(event){
event.preventDefault();
var anchor = [];
if( $(this).prop('tagName').toLowerCase() == 'a' ) {
anchor = $(this).attr('href').match(/^.*(#.+)$/i);
} else {
anchor = $(this).find('a').attr('href').match(/^.*(#.+)$/i);
}
if( anchor !== null && $(anchor[1]).length > 0 ) {
var target = $(anchor[1]);
$('html,body').animate({
scrollTop: target.position().top
}, 400);
}
});