views:

90

answers:

4

Ok, here's what I'm trying to do. I have a DIV box with a child element set with DISPLAY: NONE;. I'm trying to use Jquery so that when the mouse enters the parent DIV box, the child element is made visible, and then hides when the mouse leaves the parent DV. There will be multiple divs on the page with these classes. For some reason it's not working. Any ideas? Here's my code:

HTML:

<div class="parent">  
     <span class="handle" style="display: none;">My Handle</span>
     <p>Child Text</p>
</div>

Javascript:

$(document).ready(function () {
    $('.parent').mouseenter(function(){
        $(this).next('.handle').show();
    });
    $('.parent').mouseleave(function(){
        $(this).next('.handle').hide();
    });
})
+3  A: 

Use find instead:

$(document).ready(function () {
    $('.parent').mouseenter(function(){
        $(this).find('.handle').show();
    });
    $('.parent').mouseleave(function(){
        $(this).find('.handle').hide();
    });
})

Or even better, try this:

$(document).ready(function () {
    $('.parent').hover(function(){
        $('.handle', this).show();
    },
    function(){
        $('.handle', this).hide();
     });
   );
})
Sarfraz
That did it! Thanks so much!
John K
@John K: You are welcome..........
Sarfraz
I would recommend specifying the element type. It speeds up the query a bit.
ChaosPandion
@ChaosPandion: The OP might want to change element from `span` to some other element. Keep it generic where possible so as to avoid future issues.
Sarfraz
A: 

I recommend you use hover. This means you only need to run the query once.

$('div.parent').hover(
    function () {
        $(this).children('span.handle').show();
    },
    function () {
        $(this).children('span.handle').hide();
    }
);
ChaosPandion
+2  A: 

You can achieve your goal without jQuery:

 .parent .handle{  
    display:none;  
 }  
 .parent:hover .handle{
    display:inline;
 }

<div class="parent">  
   <span class="handle">My Handle</span>
   <p>Child Text</p>  
</div>

And you should probably use CSS only because it removes the need for Javascript.

Tested FF and Safari

Christopher Altman
This will not work. Once the element is hidden I was unable to detect it. *Tested in Firefox only*.
ChaosPandion
This is because I spelled display wrong. Try again.
Christopher Altman
I feel really dumb.
ChaosPandion
How do you think I feel? ;)
Christopher Altman
In the end, I'm using jQuery for more then just changing the display, but this is a good solution for the problem as I presented it. Thanks!
John K
A: 

Try this, instead:

$(document).ready(function () {
    $('.parent').mouseenter(function(){
        $(this).next('.handle').show();
    }).mouseleave(function(){
        $(this).next('.handle').hide();
    });
})
DKinzer