views:

2471

answers:

4

Hi,

I've just learnt a bit jQuery, and am trying to use it for a simple color-changing effect. Let's say I have two <div>s, #foo and #bar. #foo has a lot of URLs, and has the following CSS defined:

#foo a {color: blue; border-bottom: 1px dashed blue}
#foo a:hover {color: black; border-bottom: 1px solid black}

now I would like to change the color of the links (a:link) in #foo when the user clicks #bar, but keep the a:hover color untouched, so I write my function like this:

//...
$("#bar").click(function () {
  $("#foo a").css("color", "red");
});
//...

The problem is, while this function does change all the links into red, the a:hover color is lost, i.e. when a user moves the cursor on to the links, they will stay red, not turn black as I expected.

Since I see what jQuery does is put an inline style to <a>s within #foo, makes them into <a style="color:red;" href="...">, I guess this will overwrite the :hover pseudo-class. As the inline style attr for pseudo-class has not been implemented by anyone afaik, I doubt if I can get my intended effect at all...

still, is there any solutions that do not require me to write something like

$("#foo a").hover(
    function(){ $(this).css("color", "black");},
    function(){ $(this).css("color", "blue");}
)

?

thanks.

+1  A: 

!important seems to make css property stronger than inline style, at least in Firefox. Try to change your styles to something like this:

#foo a:hover { color: black !important; }
che
Awesome, it works for both IE7 and Chrome. have not FF installed but I think it will work for FF as you said. Thanks a lot.
Metaphox
+1  A: 

Maybe you could remove the class you added when you hover over the links, like this:

$('#bar').click(function() {
  $('#foo a').css('color', 'red');
});
$('#foo').hover() {
  $'#foo a').removeCss('color', 'red');
});

[EDIT]: You may need to add an IF statement to see if the class is there in the first place.

BBetances
thanks my friend, che's solution works, but I was trying to do what you said before I saw both your and his answers :)
Metaphox
A: 

AFAIK, jQuery can't set pseudo classes. However, there's another way:

http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

SlappyTheFish
A: 

AFAIK, jQuery can't set pseudo classes. However, there's another way:

http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/