0

I need to set the css styles to the following elements as follows using jQuery

#hdr-nav-wrapper ul li:hover a{ 
    background-color:#0294ca;
}

 #hdr-nav-wrapper ul a:hover{ 
   background-color:#00aeff;
} 

Except that the actual color will have to be dynamic based on whatever the background color of a div with id of "TestDiv". This site has a theme engine where users can change colors using a color theme palette. I am appending a nav bar to the top of the site but I want to have the background of the nav bar as the same as whatever "TestDiv" currently has.

How do I convert the above css to jQuery with that dynamic logic?

1

1 Answer 1

3

Use jQuery .hover() and .css(). To make the swapping of the background color easier, wrap your <a> tag in a "display-block" element that can match the dimensions of the <li>. You will only need to add/remove background color on the new wrapper element (otherwise, you would have to save the old background color in a state to revert back to on mouseout)..

Here is a demo in jsfiddle.

HTML:

<ul>
    <li><div><a>test</a></div></li>
    <li><div><a>test</a></div></li>
</ul>
<div id="TestDiv" style="background-color:blue;">&nbsp;</div>

CSS:

li {
    background-color: orange;
}

jQuery:

$('ul li').hover(function() { 
    var $el = $(this).find('div');
    if($el.length > 0) {
        $el.css('background-color', $('#TestDiv').css('background-color'));
    }
}, function() {
    var $el = $(this).find('div');
    if($el.length > 0)
        $el.css('background-color','');
});
Sign up to request clarification or add additional context in comments.

2 Comments

I may have had a slightly different idea of what you want to achieve. Are you sure you want to change the <a> background and not the <li>?
it was actually <li>. Thanks for your help!

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.