2

I am trying to show/hide the child class when parent is hovered. I have multiple class set like in Jquery $(this) Child Selector.

for some unknown reason it is not working.

What I have is

<div class="parentitem">
    <div class="childitem">
    </div>
</div>

Also

$("div.childitem").css({visibility: "hidden"});

$("div.parentitem").mouseenter(function(){
    $("div.childitem").css({visibility: "visible"});
});

$("div.parentitem").mouseleave(function(){
    $("div.childitem").css({visibility: "hidden"});
});

This works but all the children are affected. What I wanted is to affect only particular div and its child

I tried to use

$(this).children("div.childitem").css({visibility: "visible"});

$(this).parent().children("div.childitem").css({visibility: "visible"});

$(this).next("div.childitem").css({visibility: "visible"});

None of this is working for some reason.

Can somebody point me where I went wrong.

Thanks

Deepak

Community
  • 1
  • 1
Deepak Shrestha
  • 773
  • 2
  • 9
  • 25

5 Answers5

5

Try:

$("div.childitem").css({visibility: "hidden"});

$("div.parentitem").mouseenter(function(){
    $(this).find('.childitem').css({visibility: 'visible'});
});

$("div.parentitem").mouseleave(function(){
    $(this).find('.childitem').css({visibility: 'hidden'});
});

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2

Try $(this).find("div.childitem") instead of $(this).children("div.childitem").

children() finds the immediate children only, while find() searches among all children, i.e. the children's children and their children and so on.

If that still doesn't work, I suggest to anaylze the order in which all related event handlers are called. Might be that the result of the mouseenter event handlers is instantly undone by some other event handler.

In Chrome or with Firebug in Firefox you can log to the console. E.g. for Chrome it's console.log(text_or_object).

robert
  • 3,484
  • 3
  • 29
  • 38
  • Try to debug your event handlers, i.e. try to understand in which order they're called and what they're *actually* doing to the page. – robert Sep 16 '11 at 13:13
0

This might be interesting: http://jsfiddle.net/DrkwB/2/

I just modified an existing example to accommodate multiple content areas and then the particular parent that is hovered on, its child element is hidden or shown accordingly.

Peter
  • 6,509
  • 4
  • 30
  • 34
0

I think this is what you'll need:

$("div.parentitem").mouseenter(function(){
    $(this).find("div.childitem").css({visibility: "visible"});
});
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
0

You need to use $(this) as the selector context ie

$("div.childitem",$(this))

Though there is probably a more elegant solution...

El Ronnoco
  • 11,753
  • 5
  • 38
  • 65