Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseOver event to change TD background and text

I need to change the td background to grey and text in another td when the user's mouse goes over the first mentioned td.

I have done this so far:

<td onMouseOver="this.style.background='#f1f1f1'" onMouseOut="this.style.background='white'">

but this only changes the background of the first td and does not change the text in the second td.

Any ideas please?

like image 394
C.. Avatar asked Feb 04 '11 12:02

C..


1 Answers

Have a look at this:

function highlightNext(element, color) {
    var next = element;
    do { // find next td node
        next = next.nextSibling;
    }
    while (next && !('nodeName' in next && next.nodeName === 'TD'));
    if (next) {
        next.style.color = color;
    }
}

function highlightBG(element, color) {
    element.style.backgroundColor = color;
}

HTML:

<td onMouseOver="highlightBG(this, 'red');highlightNext(this, 'red')" 
    onMouseOut="highlightBG(this, 'white');highlightNext(this, 'black')" >

DEMO

Note that adding the event handler in the HTML is not considered to be good practice.


Depending on which browser you want to support (it definitely won't work in IE6), you really should consider the CSS approach which will work even if JS is turned off. Is much less code and it will be easier to add this behaviour to multiple elements:

td:hover {
    background-color: red;          
}

td:hover + td {
    color: red;   
}

DEMO

like image 65
Felix Kling Avatar answered Nov 11 '22 06:11

Felix Kling