views:

79

answers:

1

So let's say I have a block of nested divs:

<div class='nested'>
 <div class='nested'>
  <div class='nested'></div>
 </div>
</div>

I want this kind of behavior:

  1. Hover on a div. That particular div changes background color, and its children don't.
  2. Hover on that div's child. Again, it changes color while its children don't, AND(important) its parent reverts to its original color.
  3. Go back up to the parent div. Child reverts to original color, parent once again changes color.

The first two steps are easy:

$(function() {
  $('.nested').bind('mouseenter',function() {
    $(this).css('background-color','#EEE');
    $(this).parent().css('background-color','white');
  }).bind('mouseleave',function() {
    $(this).css('background-color','white');
  });
});

But I hit a snag on that last step, because when I enter a child div the mouseenter event is still active on the parent; all I've done is make it look like it isn't. The only way to trigger the mouseleave on the parents is to exit the nested block entirely and enter again. Is there a way around this?

+2  A: 

Add a mouseleave event to the parent and remove the parent's color on that.

$(function() {
  $('.nested').bind('mouseenter',function() {
    $(this).css('background-color','#EEE');
    $(this).parent().css('background-color','white');
  }).bind('mouseleave',function() {
    $(this).css('background-color','white');
    // put the color back on the parent
    $(this).parent().css('background-color', '#EEE');
  });

  // remove the color from the parent
  $(".parent").bind("mouseleave", function() {
    $(this).css('background-color','white');
  });
});
Joel Potter