Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How can I change the background color on all TDs in a TR at the same time on Mouseover/Mouseout?

When I mouseover one TD in a row I want all the TDs to change background color at the same time, then reverse on mouseout.

How do I do this?

like image 712
Warwick Avatar asked Aug 03 '11 12:08

Warwick


People also ask

How do you change the background color in JavaScript?

To change background color with javascript you can apply style. background or style. backgroundColor on the element you want to change background for. The below example changes the background color of the body when you click an element using style.

How do I change the background color of a whole web page?

To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color.

Which property is used to change the background color in JavaScript?

The background-color CSS property sets the background color of an element.

How do you change the background color in HTML style?

How to Add Background Color in HTML. To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.


2 Answers

In CSS you could do

tr td { background-color: white }
tr:hover td { background-color: black };

or just

tr { background-color: white }
tr:hover { background-color: black };

if the tds don't have their own background color.

Both should make the row black on mouseover, and white otherwise.

You could also do it in Javascript of course, but that isn't necessary (except for IE6, which doesn't understand the :hover pseudo-class on anything but <a> tags)

like image 158
Flambino Avatar answered Oct 09 '22 19:10

Flambino


var tds = document.getElementsByTagName("td");
for(var i = 0; i < tds.length; i++) {
    tds[i].onmouseover = function() {
       this.parentNode.style.backgroundColor = "#ff0000";
    }
    tds[i].onmouseout = function() {
      this.parentNode.style.backgroundColor = "#fff";  
    }
}

This actually changes the background colour of the parent tr, not each td, but it could be easily modified to do so. You could also attach the events to the tr elements instead of the td elements, and then you wouldn't have to use parentNode, but I don't know whether you need to do other stuff in the event handler specifically related to the td.

like image 31
James Allardice Avatar answered Oct 09 '22 20:10

James Allardice