Change color of <tr> when element inside is in focus
It is technically possible to make a tr
element focusable, on sufficiently new browsers, by using a tabindex
attribute on it, e.g. <tr tabindex="1">
.
However, the method of focusing is browser-dependent, and focusable table rows can be a usability nightmare. For example, both on IE and on Firefox, the row is focused on when the TAB key is used suitably, but a focused row does not take input. The use would need to hit TAB again to get to the input field. On Firefox, but not on IE, the row can also be focused on by clicking, though not by clicking on the input field (since that would focus on that field). If you use label
markup, as recommendable for usability and accessibility, e.g.
<table>
<tr tabindex="1">
<td><label for="name">Name</label></td>
<td><input type="text" name="name" id="name"></td>
</tr>
</table>
… then clicking on the label focuses on the input field (one of the reasons for using label
markup!), not on the row element.
No. There's no subject selector in CSS3, there will be one in CSS4 though.
EDIT:
A pure JavaScript solution could be
var i;
var inputs = document.querySelectorAll("tr > td > input");
for(i = 0; i < inputs.length; ++i){
inputs[i].addEventListener('focus',function(e){
this.parentNode.parentNode.className += ' highlight';
});
inputs[i].addEventListener('blur',function(e){
this.parentNode.parentNode.className = this.parentNode.parentNode.className.replace(/\s*highlight\s*/ig,' ');
});
}
However, this won't work in IE≤7, as versons prior 8 don't know document.querySelectorAll
(demonstration). If you want a care-free cross-browser solution you could use jQuery and the following code (demonstration):
$("tr > td > input").focus(function(e){
$(this).parent().parent().addClass('highlight');
}).blur(function(e){
$(this).parent().parent().removeClass('highlight');
});
Don't forget to add a class tr.highlight
to your CSS. Keep in mind that jQuery will drop support of old browsers in future releases (see Browser Support), so you'll have to use jQuery 1.x for IE ≤8.
What about using :focus-within...
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
</table>
CSS:
tr:focus-within {
background:yellow;
}
Fiddle
What helped me. As the chosen answer did not work for me.