Skip to content
Advertisement

Invoking JS Interop Function for DOM element located in submenu in Blazor

I am trying to invoke a JS function that creates a modal on user click through JS Interop in Blazor. The thing is, the function is using a onclick event for a DOM element that is inside a Blazor submenu. When that DOM Element is outside the submenu in the side navbar, it works fine. When I put that element inside the submenu, Blazor complains that it cannot set property 'onclick' of null

Here is my navbar HTML and JS Interop code

JavaScript

I am trying to use onclick with this id element

JavaScript

It is inside the submenu it created. When I put it outside the submenu into the main nav menu, the JS function does not complain and it works fine.

I have also tried doing this

JavaScript

This stops the error but clicking the element does nothing. How can I go about fixing this? I am trying to research about the Blazor LifeCycle as I feel this is a rendering issue but I am having a hard time understanding what I can do.

Here is also the JS function that I am trying to call

JavaScript

Advertisement

Answer

Your first error, cannot set property 'onclick' of null, happens because the subnav portion is not expanded when the navbar is first rendered, so the addBtn element isn’t found in the DOM yet when you call var btn = document.getElementById("addBtn");

The second issue is because your if() statement only runs once, on first render, while expandSubnav is false. So your await JS.InvokeVoidAsync("createModal"); line will never get executed.

If you notice in the @code block there’s a method for toggling the collapseNavMenu:

JavaScript

If you did something similar, but for expandSubnav, you could use that as an opportunity to hook in your createModal code. You only want to do it once, so you’d probably want to keep track of that too. Something like:

JavaScript

And then hook that into your NavLink:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement