Reputation: 207
Im trying to click an element and get the offsetTop position. Im trying to do this with this javascript code:
window.ShowAlert = function myFunction(event) {
console.log("Hello World.");
alert(event.target.offsetTop);
}
This code is inside a folder in my wwwroot and in my Index.razor I have this code:
@inject IJSRuntime jsRuntime
<div>
<Member OnClick="MemberFunction" />
</div>
@code {
void MemberFunction()
{
jsRuntime.InvokeAsync<object>("ShowAlert");
}
}
When I run this the console log appears as expected but the alert doesn't, and I tried to change the alert to appear "Hello World" and works fine, the problem is the event.target
.
Why the alert with the offsetTop position is not working?
Thank you for your attention.
Upvotes: 3
Views: 871
Reputation: 4673
You can pass the elementRef to the javascript method using @ref:
@inject IJSRuntime jsRuntime
<div>
<Member @onclick="MemberFunction" @ref="memberRef"/>
</div>
@code {
private ElementReference memberRef;
void MemberFunction()
{
jsRuntime.InvokeAsync<object>("ShowAlert", memberRef);
}
}
EDIT
You will need to modify the javascript:
window.ShowAlert = function myFunction(element) {
console.log("Hello World.");
alert(element.offsetTop);
}
NOTE
I changed OnClick to @onclick.
You can see a demo on BlazorFiddle -> https://blazorfiddle.com/s/61o1g7ef
Upvotes: 4