Zach Gates
Zach Gates

Reputation: 4130

Hover over child and change parent background color?

I have my html code:

<div id="bot-bar">
    <nav class="main-nav" id="main">
        <a id="home" href="/">Home</a>
        <a id="events" href="events.php">Events</a>
        <a id="news" href="news.php">News</a>
        <a id="ranks" href="ranks.php">Ranks</a>
        <a id="media" href="media.php">Media</a>
    </nav>
</div>

When I hover over an <a> tag, it should change the color of the bot-bar div. How can I accomplish this?

Upvotes: 1

Views: 1011

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

var botBar = $('#bot-bar');

botBar.find("a").hover(function(){
   botBar.css({backgroundColor: "red"});      // mouseenter event
}, function(){
   botBar.css({backgroundColor: "green"});    // mouseleave event
});

Or somewhat shorter (less performant but to show some possibilities):

$('#bot-bar a').hover(function( ev ){
   $(this).closest("div").css({background: ev.type=="mouseenter"?"red":"green"});
});

To get the currently hovered element background:

var botBar = $('#bot-bar');
var botBarBg = botBar.css("background-color");

botBar.find("a").hover(function(){
   var bg = $(this).css("background-color");
   botBar.css({backgroundColor: bg});      // mouseenter event
}, function(){
   botBar.css({backgroundColor: botBarBg});    // mouseleave event
});

jsBin demo

Upvotes: 4

Related Questions