Scrolling to a control with JavaScript and Blazor

Imagine you have a very long HTML table with a form at the bottom. What you would like to do is, when a user clicks on a table row, it jumps down to the table so they can edit it. After saving the form, the screen jumps back to the row you clicked:

I had created a Blazor page where I needed to do just that. Here are the steps I took.

I created an HTML table with a unique ID for each row. Each row also had its “onclick” event pointing to a Blazor method, ScrollToControl, which took as a parameter the ID:

<div class="col-lg-8">
    <table class="table table-bordered table-striped">
        <tbody>
            @foreach (var c in Coasters)
            {
                <tr id="@c.Id" onclick="@(() => ScrollToControl(c.Id))">
                    <td>@c.Name</td>
                </tr>
            }
        </tbody>
    </table>
</div>

At the bottom of the screen, I defined a form. In this example, it’s just another table. The important thing is the id tag, which will be used in a coming JS function:

<div class="col-lg-8">
    <table id="entryform" class="table">
        <tr>
            <td>Test Form</td>
        </tr>
    </table>
    <input type="button" value="Save" onclick="@Save" class="btn" />
</div>

I defined the “Save” method to call the JS method for scrolling up. Remember to inject the IJSRuntime service on the Blazor page:

@inject IJSRuntime JsRuntime
    
private void Save()
{
    JsRuntime.InvokeVoidAsync("scrollToTableRow");
}

The ScrollToControl method which is called when a row is clicked. It also uses IJSRuntime to call a JavaScript function and passes the id of my form:

   private async void ScrollToControl(int id)
    {
        JsRuntime.InvokeVoidAsync("scrollToControl", "entryform", id);
    }

I then created JavaScript methods to do the scrolling, and these were put in the _Host.cshtml file. The “scrollToControl” method is used when clicking on the table row to jump down to the form. The “scrollToTableRow” method jumps the user back to the row they clicked:

        function scrollToControl(controlId, id) {
            currentRow = id;
            document.getElementById(controlId).scrollIntoView();
        }

        function scrollToTableRow() {
            document.getElementById(currentRow).scrollIntoView();
            currentRow = '';
        }

That is about it.

  1. Leave a comment

Leave a comment