0

I have some JavaScript which is changing an image correctly but once it has been called, my a:hover CSS code no longer works.

Looking with 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 the JavaScript and not have the a:hover code overriden by the element.style rule?

KevinUK
  • 5,053
  • 5
  • 33
  • 49
  • Where is your CSS that sets the a:hover style? Please post more code. – roryf May 05 '09 at 16:03
  • need to see more code. But are you sure that you HTML is still as it was after the transformation? I assume your writing your styles inline. may i suggest having them properly written in referenced CSS file – nickmorss May 05 '09 at 16:12
  • Why don't you use CSS for this? Also, can you post your JavaScript? – Keith Donegan May 05 '09 at 16:00

2 Answers2

1

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

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

Unfortunately the inline style always wins. In the above sample the link will always be red. As Daniel White said jQuery would be very useful here. Although you may be able to get around this issue in two ways.

One, Generate the style using javascript to write a style tag

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

or two, Manually setup mouseenter/mouseleave events to handle your hover style

Update

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

<style type="text/css">
  a { background: blue; }
  a:hover { background:green !important; }
</style>
<a href="#" style="background:red;">link<a>
bendewey
  • 39,709
  • 13
  • 100
  • 125
  • Aha! Since you said element.style is the same as inline style I just added !important to my a:hover and it stops element.style overriding my a:hover rule. Yes, JavaScript is messy instead of CSS but I'm using a fancy Javascript menu script and so forced down that route a bit. – KevinUK May 05 '09 at 16:11
  • great, I added that as #3, although it probably should be #1 since its IMHO the cleanest approach. – bendewey May 05 '09 at 16:14
0

I was also frustrated about this CSS js style gap so I build
methods to apply style from js with a CSS string

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

Community
  • 1
  • 1
bortunac
  • 4,642
  • 1
  • 32
  • 21