search

Home  >  Q&A  >  body text

How to implement row hover in Blazor wasm

<p>I have a Blazor table component that changes based on the number of variable rows in a collection: </p> <pre class="brush:php;toolbar:false;"><table id="MyTable" class="table table-hover"> <thead> <tr> <th>Project name</th> <th>Description</th> <th>Uploader</th> <th>Upload Date</th> </tr> </thead> @foreach (var item in Items) { <tbody> <tr> <th>@item.Name</th> <th>@item.Description</th> <th>@item.UserName</th> <th>@item.UploadDate.ToString("dd-MM-yyyy")</th> <th><button type="button" class="btn btn-primary" @onclick="() => DoSomething()">Do Work</button></th> </tr> </tbody> } </table></pre> <p>What I need to do is, when the mouse is hovering over a row,<em>only</em>that specific element of that row becomes enabled. </p> <p>For example, if this table has 10 rows (1-10), when I hover over row 1, only the button for row 1 should be visible and clickable. Other buttons whose parent row has no hover should not be enabled. </p> <p>In Blazor, how do I enable only the <em>buttons on that specific row</em> when hovering over a row? </p>
P粉425119739P粉425119739552 days ago542

reply all(1)I'll reply

  • P粉252116587

    P粉2521165872023-08-14 11:48:16

    As mentioned in the comments, there are some reasons why you might not want to show child elements on mouseover: it relies on the user using the mouse. Alternatively, the entire row can be made clickable, which may provide a better user experience.

    Though for the sake of completeness, here is how to solve the problem I asked:

    In the Razor page, add CSS Id selectors for the row (parent) and button (child) HTML tags:

    @foreach (var item in Items)
        {
            <tbody>
                <tr id="FileTableRow">
                    <th>@item.Name</th>
                    <th>@item.Description</th>
                    <th>@item.UserName</th>
                    <th>@item.UploadDate.ToString("dd-MM-yyyy")</th>
                    <th><button id="FileTableRowButton" type="button" class="btn btn-primary" @onclick="() => DoSomething()">Do Work</button></th>
                </tr>
            </tbody>
        }

    We can then use CSS to apply styles to the button (child) on hover over the row (parent):

    #FileTableRowButton {
      visibility: hidden;
    }
    
    #FileTableRow {
      &:hover {
        #FileTableRowButton {
          visibility: visible;
        }
      }
    }

    Depending on your use case, you may want to apply different styles. For example, use display: none; instead of visibility: hidden;

    reply
    0
  • Cancelreply