0

I am writting CSS dynamically in Javascript. I am trying to specify(in Javscript) that when the mouse hovers over a paragraph element its text colour changes.

Is there a way to do this without having to resort to the onMouseOver way, something like...

myEle.style.colorHover = "#FFFFFF";

// Maybe this works?
var ele = document.createElement("p");
ele.style.colorHover = "#FFFFFF";
ele.style.backgroundColorHover = "#000000";
ele.style.color = "#000000";
ele.style.backgroundColor = "#FFFFFF";
sazr
  • 24,984
  • 66
  • 194
  • 362
  • 4
    See http://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript or http://stackoverflow.com/questions/714655/how-can-i-set-a-css-hover-on-a-dom-created-element-in-javascript - it's exactly what you are looking for. – ThiefMaster Nov 02 '11 at 22:35
  • 1
    Given the lack of support for the *hover* pseudo-class in IE, hover effects are usually implemented using listeners for mouseover/out events on a parent element (e.g. on a tbody or table element for table rows). – RobG Nov 02 '11 at 23:22
  • If you are doing this to more than 1 elemnt on the page, i'd recommend using jQuery and the hover() handler http://api.jquery.com/hover/ makes it s a little nicer to manage IMO. – sweetroll Nov 03 '11 at 01:05

1 Answers1

0

Just wrap your text in an additional A tag and use :hover to change the color of your text.

Of course you'll probably want to create a class and add it via JavaScript.

JavaScript:

ele.setAttribute("class", "myClass");

CSS:

P A.myClass
{
 /* colors when not hovering */   
}
P A.myClass:hover
{
 /* colors when hovering */
}
Matthew
  • 8,183
  • 10
  • 37
  • 65