JSFiddle - React, Tailwind, and code Playground
by gnemeth
HTML
<nav>
<a href="?section1" data-attr-scroll="section1" class="scrollto">Section 1</a>
<a href="?section2" data-attr-scroll="section2" class="scrollto">Section 2</a>
<a href="?section3" data-attr-scroll="section3" class="scrollto">Section 3</a>
<a href="?section4" data-attr-scroll="section4" class="scrollto">Section 4</a>
<a href="?section5" data-attr-scroll="section5" class="scrollto">Section 5</a>
</nav>
<div class="test" id="section1">
#1 Section
</div>
<div class="test" id="section2" data-anchor-offset="100">
#2 Section
</div>
<div class="test" id="section3">
#3 Section
</div>
<div class="test" id="section4" data-anchor-offset="200">
#4 Section
</div>
<div class="test" id="section5" data-anchor-offset="300">
#5 Section
</div>
CSS
body {
margin: 0;
padding: 0;
}
nav {
position: fixed;
top: 20px;
right: 20px;
}
.test {
height: 500px;
}
JavaScript
jQuery(document).ready(function($) {
$(".scrollto").click(function(event) {
event.preventDefault();
var defaultAnchorOffset = 0;
var anchor = $(this).attr('data-attr-scroll');
if (anchor.charAt(0) === '?') {
anchor = anchor.substr(1);
}
var anchorOffset = $('#'+anchor).attr('data-scroll-offset');
if (!anchorOffset)
anchorOffset = defaultAnchorOffset;
$('html,body').animate({
scrollTop: $('#'+anchor).offset().top - anchorOffset
}, 500);
});
});