Framework: .Net6.0
C#: 10.0
How do I navigate to an Id after the page finishes rendering? I have a virtualized list of items, one item out of the list gets assigned an Id.
I want to be able to scroll down to this Id after the page finishes rendering.
I’m able to scroll down ‘manually’ simply by adding ‘#IdName’ to the end of the url. I’m unable to get blazor to scroll down to this Id using the Navigation Manager.
I’ve tried the following in OnAfterRenderAsync
:
_navigationManager.NavigateTo("/test#testscroll");
and the following JS and C# code in OnAfterRenderAsync
await JsRuntime.InvokeVoidAsync("scrollToElementId", "");
Javascript
scrollToElementId = (elementId) => {
elementId = "testscroll";
console.info('scrolling to element', elementId);
var element = document.getElementById(elementId);
if(!element)
{
console.warn('element was not found', elementId);
return false;
}
element.scrollIntoView();
return true;
}
The JS file has been added to wwwroot/Javascript/main.js
and
<script src="Javascript/main.js"></script>
added above
<script src="_framework/blazor.server.js"></script>
in _Layout.cshtml
The JS listed above DOES work, but only for items that are not in the virtualized list. If I add a static div to the bottom of the list, out side the Virtualize tag, it will scroll to the bottom. But if I try to use a Id from and item inside the Virtualize tag, it does not scroll.
I receive the element was not found
console warning from the JS, when using Id’s from the virtualized list.