'Some JQuery function not working after executing Blazor.Run from file blazor.server.js

I created the Blazor Server application (.net 5.0). Added it to startup.cs services.AddServerSideBlazor(). Then integrated the Bootstrap template, and the trials with adventures began.. In the _Host.chtml file, section, I added <script src="assets/js/sb-admin-2.js"></script> that contains the following definition

$("#sidebarToggle, #sidebarToggleTop").on('click', function (e) {
  $("body").toggleClass("sidebar-toggled");
  $(".sidebar").toggleClass("toggled");
  if ($(".sidebar").hasClass("toggled")) {
    $('.sidebar .collapse').collapse('hide');
  };
});

and it is associated with a part of the markup

  <!-- Sidebar Toggler (Sidebar) -->
  <div class="text-center d-none d-md-inline">
    <button class="rounded-circle border-0" id="sidebarToggle"></button>
  </div>

In the same place, in _Host.chtml file, the last directive I specified

<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
    document.addEventListener("DOMContentLoaded",
      function () {
        Blazor.start({
          logLevel: 1, // LogLevel.Debug
          configureSignalR: builder => builder.configureLogging("debug") // LogLevel.Debug
        });
      });
  </script>

Now about the problem. With this configuration, the jQuery code defined in the .js file is not executed by the click event.

Experimentally, I found out that if you do not execute the Blazor.Start() directive, then the button with id=sidebarToggle is pressed and the jQuery defined in the .js file is executed.

when blazor.run() was not running

after execution, this handler is not there



Solution 1:[1]

After hitting the same issue, I came up with a simple solution. I wrapped all my DOM-Ready functions in one wrapper init function and then called it After Render of the page.

JavaScript (Layout.cshtml)

function initUi() {
    (function ($) { /** sidebar event logic here **/ })(window.jquery);
}

Blazor (MainLayout.razor)

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("initUi");
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chris