Programmatically scroll the webpage to top using Blazor Floating Action Button (FAB) component
The Blazor Floating Action Button (FAB) component 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 the FAB component. For a quick start with the 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 the 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 7Blazor Server app, include in the ~/Pages/_Host.cshtmlfile. - For
.NET 8Blazor Web app with server rendering, include in the ~/Components/App.razorfile.
<body>
...
<script>
function scrollToTop() {
document.documentElement.scrollTop = 0;
}
</script>
</body>
Additional References
For more information about the Blazor FAB component, you can refer to the following sections: