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?
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.
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.
The background-color CSS property sets the background color of an element.
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.
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With