Adding "mousedown" event listener from JS doesnt work on RadzenListBox

 document.querySelectorAll("rz-multiselect-item").forEach(item => {
     console.log("adding event listener", item);
     item.addEventListener('mousedown', (event) => console.log("test"));
 });

I add mousedown event listener like this in a js file. "adding event listener" log is visible. But when i click list items "test" log doesn't appear in console. if i select a regular vanilla html element with "querySelectorAll" i can see "test" log if i click that element.

Hi @kem,

I think your selector should look like this (starting with a . which is used for class name selectors):

document.querySelectorAll(".rz-multiselect-item")
1 Like

Hi. It already is starting with "." on my local. Sorry i forgot to put it in my post. As i said, it selects correct elements but event doesn't fire.

this log works: console.log("adding event listener", item);
this one doesn't: console.log("test")

I suspect the code adds the event handlers to a different listbox. This works as expected:

<div class="rz-p-sm-12 rz-text-align-center">
    <RadzenListBox class="my-list" AllowClear="true" @bind-Value=value
                    LoadData=@LoadData AllowFiltering="true"
                   Data=@customers TextProperty="@nameof(Customer.CompanyName)" ValueProperty="@nameof(Customer.CustomerID)" Style="width: 100%; max-width: 400px; height: 200px"
                   InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "select company" }})" />
</div>

<script>
    setTimeout(() => {
        document.querySelectorAll(".my-list .rz-multiselect-item").forEach(item => {
        item.addEventListener('mousedown', event => console.log('test'));
      });
    });
</script>
1 Like

I don't have any other ListBox.

setTimeout method makes the difference. Solved thanks. But I don't understand how that works. I see that even though we don't provide a time value for setTimeout method it will not execute the code immediately:

Due to JavaScript's event loop mechanism, this does not execute immediately but runs after the current code block has completed.

When I debug that JS code (without setTimeout), specifically "item" variable, I can see "li" tag in that. I have the correct element but event doesn't attach:

document.querySelectorAll(selector).forEach(item => {
    //I have the "li" element here. 
    item.addEventListener('mousedown', (event) => console.log('test'));
});

Any idea how that works?

I think the list view is not fully initialized when you run the code without setTimeout. Perhaps it is later updated by Blazor hence the event handlers are wiped.

1 Like