I'm new to Blazor and I've created a pretty simple Webassembly app. I want a href link to go to a div lower down the page when I click on it, but the Javascript click event won't work. In the Index.razor page the JsRuntime.InvokeVoidAsync("clicker")
is working and the alert("In clicker")
happens as the page loads, but the click / href to go the "intro" div will not work for love nor money :-/
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Blazor App</title>
<!--script type='text/javascript' src='./scripts/app.js'-->
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.webassembly.js"></script>
<script>
function clicker() {
alert("In clicker"); // this works
document.getElementById('skip').onclick = function(e){
alert("clicked"); // this works but the page still won't scroll to the "intro" div :(
}
}
//clicker();
</script>
</body>
</html>
Index.razor (@code section is at top of page)
@page "/"
@code {
[Inject]
protected IJSRuntime JsRuntime { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
JsRuntime.InvokeVoidAsync("clicker");
}
}
}
// This link won't go to the intro div when clicked :(
<a id="skip" class="skip" href="#intro">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
If anyone could shed some light on this it would save my week.
There is no need for JavaScript here.
If you add a specific target to your markup, it will just work.
You can use target="_top" to avoid Blazor navigation interception.
<a class="skip" href="#intro" target="_top">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Note that target="_top"
just directs the browser to navigate within the topmost frame in the window, it does not mean you will scroll to the top!