Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Focus to a table row <tr>?

I have a table generated with AngularJS.
Here's my HTML:

<table class="my_table">
    <thead>
         <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Celphone</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="contact in contacts">
            <td>{{contact.Name}}</td>
            <td>{{contact.Address}}</td>
            <td>{{contact.Celphone}}</td>
        </tr>
    </tbody>
</table>

I want each row to change color when "hover" and a different color when "clicked", so I tried this with CSS:

<style>
.my_table tbody tr:hover {
   background-color: #7fccee; /*--- this is a blue color when hover ---*/
}
.my_table tbody tr:focus {
   background-color: #f3f3f3; /*--- this is a gray color when clicked---*/
}
</style>

The hover works perfectly, but the Focus is not working! (The weird thing is that in the browser console, if I select the row and "force element state :focus" then it applies the focus to the row)

I also tried using a SCRIPT with jquery:

$(document).ready(function() {
   $('.my_table tbody tr').click(function() {
      $(this).addClass('active'); //I'm adding the color gray with css to '.active'
   });
});

But this won't work too, what am I doing wrong?

like image 955
Soul Eeater Avatar asked May 23 '18 15:05

Soul Eeater


1 Answers

The :focus pseudo class only works with form elements such as <input>, <button> etc. You can add it to a non-form element like <tr> by adding tabindex, e.g.:

<tr tabindex="0">

Then apply the CSS as normal.

.my_table tbody tr:hover {
  background-color: blue;
}

.my_table tbody tr:focus {
  background-color: red;
  outline: 0; /*remove outline*/
}
<table class="my_table" border>
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Celphone</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="contact in contacts" tabindex="0">
      <td>{{contact.Name}}</td>
      <td>{{contact.Address}}</td>
      <td>{{contact.Celphone}}</td>
    </tr>
  </tbody>
</table>
like image 135
Stickers Avatar answered Sep 28 '22 05:09

Stickers