Articles in this section
Category / Section

Programmatically scroll the webpage to top using Blazor Floating Action Button (FAB) component

2 mins read

The Blazor Floating Action Button (FAB) component that appears over all the contents of a web page, making it easy to perform primary actions. When developing web applications with Blazor, you may want to provide users with a quick way to scroll back to the top of the page when large contents are present.

This article explains how to programmatically achieve this functionality with ease using FAB component. For a quick start with FAB component, refer to this link.

Add the FAB component

First, include the FAB component on your page where you need to perform the page scroll action and bind the OnClick event to the FAB.

@using Syncfusion.Blazor.Buttons


<SfFab IconCss="e-icons e-arrow-up" title="Page Top" OnClick="OnFabButtonClick"></SfFab>

Define click event method

By using the Blazor IJSRuntime interface, invoke the JavaScript function call within the OnFabButtonClick method which triggers the scrollToTop function to scroll the page to top.

@inject IJSRuntime JSRuntime

@code {
    private void OnFabButtonClick()
    {
        // JS interop call to perform scroll top
        JSRuntime.InvokeVoidAsync("scrollToTop");
    }
}

Define JsInterop function

To set up the JavaScript function call, you can include it in your App.razor or _Host.cshtml file:

  • For .NET 7 Blazor Server app, include in the ~/Pages/_Host.cshtml file.
  • For .NET 8 Blazor Web app with server rendering, include in the ~/Components/App.razor file.
<body>
    ...
    <script>

        function scrollToTop() {
            document.documentElement.scrollTop = 0;
        }

    </script>
</body>

Scroll-top-using-FAB.gif

Additional References

For more information about the Blazor FAB component, you can refer to the following sections:

Demo.zip
Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied