0

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");    
}

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

+1, though OP might want to use .find() instead of .children() if there are anchor elements that aren't immediate children of the parent div.
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.