JSFiddle - React, Tailwind, and code Playground

by Silambarasan_sundaram

HTML

<div>
    <a class="link" href="#section1">Section1</a>
    | <a class="link" href="#section2anchor">Section2</a>
    | <a class="link" href="#section3">Section3</a>
    | <a class="link" href="#section4anchor">Section4</a>
    | <a class="link" href="#section5">Section5</a>
</div>
<div style="height: 2000px;">
    <div class="section" id="section1" data-anchor-offset="5" style="height:100px;border: grey 1px solid;">
        Section 1
    </div>
    <div class="section" style="height:200px;border: grey 1px solid;">
        <a id="section2anchor" data-anchor-offset="10">Section 2</a>
    </div>
    <div class="section" id="section3" data-anchor-offset="60" style="height:300px;border: grey 1px solid;">
        Section 3
    </div>
    <div class="section" style="height:100px;border: grey 1px solid;">
        <a id="section4anchor">Section 4</a>
    </div>
    <div class="section" id="section5" data-anchor-offset="30" style="height:200px;border: grey 1px solid;">
        Section 5
    </div>
</div>

JavaScript

jQuery(document).ready(function($) {

    $(".link").click(function(event) {
        event.preventDefault(); 

        var defaultAnchorOffset = 0;
        
        var $anchor = $('#' + this.hash.substring(1));
                
        var anchorOffset = $anchor.attr('data-anchor-offset');
        if (!anchorOffset) // for when anchor does have the offset attribute like Section 4
            anchorOffset = defaultAnchorOffset; 

        $('html,body').animate({ 
            scrollTop: $anchor.offset().top - anchorOffset
        }, 500);        
    });
});