Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not working properly with my Blazor app

I have the following script which works just fine in a simple html file being launched from my browser:

$("*[scroll-to]").click((event) => {
    // whatever here...
});

However, when using it with Blazor, it doesn't get triggered when clicking my button.

I found a workaround, which is replacing the first line with this instead:

$(document).delegate("*[scroll-to]", "click", function (event) {

Why do I have to do that? Why would it only stop working when using Blazor?

I also have a lot of other functions that are not working, such as this one for example, which doesn't add the display: none css attribute like it's supposed to:

if (!checkoutModal)
    $("#checkoutModal").hide();

It basically does nothing, even tho it's being executed.

jQuery should be properly imported:

What can I do? Why is this happening and how can I fix it?

like image 963
Matt Avatar asked Nov 20 '25 23:11

Matt


1 Answers

You want to use JSInterop in order to initialize jQuery objects in your Blazor App. Define a JavaScript init function you should call from Blazor to perform the initialization. This function should ordinarily be called only once. You should call it from the life cycle OnAfterRender(Async) pairs of methods. These methods have a boolean parameter named firstRender, which is evaluated to true the first time your Balzor App is rendered. It is important to remember that you initialize your JS objects only after the Blazor App is rendered.

Here's a link to one of my answer explaining in detail how to do that

Important: Use JS only if you can't otherwise. This is Blazor, this is not Angular or whatever. Try to convert JS widgets, such as modals into Blazor components.

Do not manipulate Blazor components by JS objects, such as jQuery, and certainly do not mutate the state of components via JS objects. They shouldn't interfere with the rendering system of Blazor, and they shouldn't touch the DOM elements which Blazor has produced. In any case, changes made by JS objects will be ignored. If, as for instance, you'll assign a value to an input text element which is bound to a property in Blazor, this value will be ignored when the page is rendered.

like image 73
enet Avatar answered Nov 22 '25 12:11

enet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!