Search code examples
javascriptjqueryrazorblazorsmooth-scrolling

I'm trying to get my Blazor Server app to run a smooth scroll J Query script


I want to smooth scroll to each of the a hrefs in the box class. My index.razor page is as follows...

<html>
<body>
    <div class="sidebar">
        <ul class="box">
            <li><a href="#home"><img class="icon"></a>O</li>
            <li><a href="#info"><img class="icon"></a>O</li>
            <li><a href="#blog"><img class="icon"></a>O</li>
            <li><a href="#contact"><img class="icon">O</a></li>
        </ul>
    </div>
    <div class="underlay">
        <section id="home">
            <h1>Hello!</h1>
        </section>
        <section id="info">
            <h1>About</h1>
        </section>
        <section id="blog">
            <h1>Service</h1>
        </section>
        <section id="contact">
            <h1>Contact</h1>
        </section>
    </div>


<script>
    $(".sidebar a").on('click', function (event) {
            if (this.hash !== "") {
    
                event.preventDefault();
    
                var hash = this.hash;
                $('html, body').animate({
                    scrollTop: $(hash).offset().top
                }, 800, function () {
                    window.location.hash = hash;
                });
            }
        });
</script>

I've tried using interop and to run the script. I believe the script is running before Blazor has compiled. Any idea how to fix this?


Solution

  • I think what you are trying to do is Fragment Navigation: When the user clicks on a link, it scrolls to the fragment, correct?

    You can do this in Blazor Server, but it requires some trickery. Fortunately, a full blog post has been written by the amazing Chris Sainty which explains it in detail here

    In a nutshell, you have to use Javascript Interop, but there is quite a bit of wiring up that must be done to get it to work. I just implemented this on a site and it works great.