Hartley Brody Hartley Brody - 3 months ago 17
CSS Question

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

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. Any help would be greatly appreciated! Thanks!

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

Answer

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

Comments