Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of <tr> when element inside is in focus

Tags:

html

css

I want to change the color of tr element when user select a text box inside it. The focus pseudo-class is not working with it. Can this be achieved without JavaScript ?

html:

<table>
<tr>
    <td>Name</td><td><input type="text" name="name"></td>
</tr>
</table>​

CSS:

tr:focus
{
    background:yellow;
}​

Update1:
Looks like there is no CSS only method. What is the easiest way to do this using JavaScript ?

like image 237
Aamir Rizwan Avatar asked Apr 15 '12 08:04

Aamir Rizwan


2 Answers

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.

like image 187
serverjohn Avatar answered Oct 19 '22 22:10

serverjohn


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.

like image 22
Zeta Avatar answered Oct 20 '22 00:10

Zeta