Search code examples
cssrazorblazorblazor-webassembly

How to automatically scroll a list?


I have created a simple UI with list of location using blazor.following figure shows my location list how actually look like.when click on one location it is highlitghted.

enter image description here

After that when press on continue button ,navigate next page and this selected location is added to following location field .

enter image description here

then if we want to edit/change the locaion, we can press above location field and redirect to the add location page again.when we come back to the add location page again ,we should be able to see the selected location is still highlited on the page.

problem:-this location list of the add location page is only scrollable.header and continue button are fixed.There are 100 locations.So if we have selected very bottom location item,when we redirect the page for editing purpose,we have to scroll untill found the location item.but it is not a best case.

requirement:-when we redirect the page for editing purpose,the page should be scrolled automatically,so that i can see the selected item.

I need to do this using blazor. anybody who knows about this please help me,i appriciate all your helps and if you need to any code parts i will provide you.


Solution

  • I had similar situation in past, I solved it using JSInterop.

    Give Id to each list item (on your location foreach loop):

    <div id="@location.Id">
    

    Upon Selecting the location you can store the Id of location in Global object which is registered as Singleton (In my case I named it as AppState).

    AppState Will Look like this:

    public class AppState
    {
      public int LoactionId { get; set; }
    }
    
    
     private void GoToLocation(int locationId)
            {
                AppState.LoactionId = locationId;
                NavigationManager.NavigateTo("locations");
            }
    

    Add this override on your list locations component.

    protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                await JsRuntime.InvokeVoidAsync("scrollTo", AppState.LocationId);
            AppState.LocationId = 0;
        }
    

    Javascript Code (Refer this):

    scrollTo = (id) => {    
        if (!id) return;
            var element = document.getElementById(id);
            if (element) {
                var headerOffset = document.getElementById('navbar').offsetHeight;//navbar class is given to header
                var elementPosition = element.getBoundingClientRect().top;
                var offsetPosition = elementPosition - headerOffset;  
                window.scrollTo({
                    top: offsetPosition,
                    behavior: "smooth"
                });
            }
    }