Applying css with javascript overrides the hover link style?

I have JavaScript that changes the image correctly, but once it was called, my CSS: hover CSS code no longer works.

Looking at firebug, the following JavaScript creates this css rule:

element.style {
background-image:url(/content/images/side_partnershipsOver.png);
}

document.getElementById('partnerships').style.backgroundImage = "url(/content/images/side_partnershipsOver.png)";

      

How can I apply JavaScript and not have the a: hover code being overridden with the element.style rule?

0


source to share


2 answers


As far as I know, setting element.style.backgroundImage is essentially the same as using inline style.

<style type="text/css">
  a { background: blue; }
  a:hover { background:green; }
</style>
<a href="#" style="background:red;">link<a>

      

Unfortunately, inline style always wins. In the above example, the link will always be red. As Daniel White said, jQuery will be of great help here. There are two ways you can get around this problem though.

One, create style with javascript to write style tag

document.write("<style type='text/css'>#partnerships { background-image:url(/content/images/side_partnershipsOver.png);}</style>");

      



or two, manually set up mouseenter / mouseleave events to handle the hover style

Update

or three, as KevinUK pointed out, use! important css tag to override the set of inline styles.

<style type="text/css">
  a { background: blue; }
  a:hover { background:green !important; }
</style>
<a href="#" style="background:red;">link<a>

      

+1


source


I was disappointed with this js css styling too, so I create styling methods from js with CSS string



elm.jCSS (cssText); elm.jCSSPseudo (cssText, pseudoElt)

0


source







All Articles