tags:

views:

1652

answers:

4

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?

A: 

Why don't you use CSS for this? Also, can you post your JavaScript?

Keith Donegan
A: 

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
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
great, I added that as #3, although it probably should be #1 since its IMHO the cleanest approach.
bendewey
A: 

I have < img alt="" style="width: 700px !important; height: 650px !important" src="http://image/testimg.jpg" />. But if I set height to 400px and width to 350px dynamically using javascript, the IE 7 & 8 takes the dynamicaly set values using javascript. whereas in firefox, it takes width to 700px and height to 650px; how IE is making problem?? Thanks in advance for any replies

parag
A: 

thanks for your reply Keith. Sorry, Its not possible for me to post the javascript. Any changes can be done done to css or DOCTYPE so that !important value used for height & width inline can overrides any value set by javascript?

parag