Reputation: 703
I am attempting to run a simple javascript function when the page is finished loading. Essentially what the code does is get the current base pathname and find the navlink with the same id and stick a class on it. Blazor's <NavLink/>
is not customizable enough for me and I'd rather do it like this. The code works, but it only appears for a fraction of a second then disappears at the same time that the following appears in console:
[2020-08-20T07:43:50.935Z] Information: WebSocket connected to wss://localhost:44346/_blazor?id=IhkBuLdowknNbyGtvWjcVA.
Here is my _Host.cshtml page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--stuff-->
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script> <!--this is the bit I added-->
var x = $(location).attr('pathname');
x.indexOf(1);
x = x.split("/")[1];
$('#' + x).addClass('onpage');
</script>
</app>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
I'm rather new to Blazor, so I'm not sure what's causing this issue.
Upvotes: 0
Views: 1032
Reputation: 9029
this is a two part answer - first to answer your question, second to show you a better way I hope.
Blazor keeps track of the UI internally - like a shadow dom, but not actually one - and it cannot track changes you make like this in JS.
When it renders the Nav it doesn't know you added that css class, so it gets replaced with the css classList that Blazor knows about.
The NavLink component has a property call ActiveClass - you can set that and it will use your own classname when the page is active
<NavLink class="nav-link" href="counter" ActiveClass="onpage">
Upvotes: 2