ZenoriInc
ZenoriInc

Reputation: 161

Format for Changing CSS using jQuery

I have a Div on my web-page where if someone hover overs it, I want to change the color of the text on all links in the parent Div. When there is a hover-over, I call the function highlight. However, the following code does not seem to work. I think there is a syntax issue because highlight2 works just fine (but doesn't achieve my main goal of changing the color of text.

function highlight(el) {
    $(el).parent().css('a:link', "{color:#28A8C8;}");
    $(el).parent().css('a:visited', "{color:#28A8C8;}");
}

function highlight2(el) {
    $(el).parent().css("background", "#FFFFFF");    
}

Upvotes: 0

Views: 260

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

As Ben D said, you have a specific syntax issue with your current code because jQuery's .css() function is expecting the first parameter to be the name of a CSS property, not a selector, and the second parameter should be the applicable value.

I'd like to suggest a better way to do the same thing though: add something like the following to your stylesheet:

div a:link, div a:visited { color:#defaultcolorhere }
div.highlight a:link, div.highlight a:visited { color:#28A8C8 }

Then you can change the colours by adding the "highlight" style to the parent div:

$(".hoverdiv").hover(function() {
   $(this).parent().addClass("highlight");
}, function() {
   $(this).parent().removeClass("highlight");
});

(If you give the divs you are hovering over a common class such as "hoverdiv" it makes them easy to select.)

Demo: http://jsfiddle.net/zSuS8/

Upvotes: 1

Ben D
Ben D

Reputation: 14479

jQuery's css() method (when setting) requires the first parameter to be a css property and the second to be a value: http://api.jquery.com/css/. You're passing in the node-type you'd like modified rather than the css property you'd like modified. If you're trying to change the color of links inside $(el).parent() then you should use:

function highlight(el) {
    $(el).parent().children('a:link').css('color', "#28A8C8");
    $(el).parent().children('a:visited').css('color', "#28A8C8");
}

If you're trying to change the color of $(el).parent() itself (assuming that $(el).parent() is a link) then you just need to:

 $(el).parent().css('color', "#28A8C8");

(no need to differentiate between visited and not visited because you're setting the same color)

Upvotes: 2

Related Questions