Search code examples
javascriptjquerycssstylesheet

Setting css styles using jQuery


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?


Solution

  • 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','');
    });