I need to find a way to change CSS :hover properties using JavaScript.
For example, suppose I have this HTML code:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
And the following CSS code:
table td:hover {
background:#ff0000;
}
I would like to use JavaScript to change the <td> hover properties to, say, background:#00ff00. know I could access the style background property using JavaScript as:
document.getElementsByTagName("td").style.background="#00ff00";
But I don't know of a JavaScript equivalent for :hover. How do I change these <td>'s :hover background using JavaScript?
Your help is greatly appreciated!
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
You can't change or alter the actual
:hover
selector through Javascript. You can, however, usemouseenter
to change the style, and revert back onmouseleave
(thanks, @Bryan).Declare a global var:
Then select your guiena pig
<td>
getting it by itsid
, if you want to change all of them thenMake a function to be triggered and a loop to change all of your desired
td
'sGo to your CSS Sheet:
And that is it, with this you are able to to make all your
<td>
tags get abackground-color: #00ff00;
when hovered by changing its css propriety directly (switching between css classes).This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
If it fits your purpose you can add the hover functionality without using css and using the
onmouseover
event in javascriptHere is a code snippet
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
CSS:
JavaScript: