Changing the child element's CSS when the parent is hovered

Hartley Brody picture Hartley Brody · Feb 21, 2011 · Viewed 190k times · Source

First of all, I'm assuming this is too complex for CSS3, but if there's a solution in there somewhere, I'd love to go with that instead.

The HTML is pretty straightforward.

<div class="parent">
    <div class="child">
        Text Block 1
    </div>
</div>

<div class="parent">
    <div class="child">
        Text Block 2
    </div>
</div>

The child div is set to display:none; by default, but then changes to display:block; when the mouse is hovered over the parent div. The problem is that this markup appears in several places on my site, and I only want the child to be displayed if the mouse is over it's parent, and not if the mouse is over any of the other parents (they all have the same class name and no IDs).

I've tried using $(this) and .children() to no avail.

$('.parent').hover(function(){
            $(this).children('.child').css("display","block");
        }, function() {
            $(this).children('.child').css("display","none");
        });

Answer

Stephen picture Stephen · Feb 21, 2011

Why not just use CSS?

.parent:hover .child, .parent.hover .child { display: block; }

and then add JS for IE6 (inside a conditional comment for instance) which doesn't support :hover properly:

jQuery('.parent').hover(function () {
    jQuery(this).addClass('hover');
}, function () {
    jQuery(this).removeClass('hover');
});

Here's a quick example: Fiddle