Search code examples
jquerymouseovermouseout

jQuery mouseover/mouseout on element with children


I have a div with one or more children. When I hover over the parent the child div should show. The problem is that when I hover over the child it hides then shows again. How can I fix this to only hide the child when I stop hovering over the parent.

jsfiddle code here

.parent{
    width: 200px;
    height: 200px;
    background: red;
}
.child{
    width: 100px;
    height: 100px;
    background: green;
    opacity: 0;
    display: none;
}
.console{
    width: 200px;
    height: 50px;
    background: pink;
}

<div class="parent">
    <div class="child"></div>
</div>
<div class="console"></div>

var hovS = 0;
$('.parent').mouseover(function(){
    if(hovS == 0){
        $('.child').css('display', 'block');
        $('.child').animate({
            opacity: 1
        });
        hovS = 1;
    }
    $('.console').append(hovS + ' - ');    
});
$('.parent').mouseout(function(){
    if(hovS == 1){
        $('.child').css('display', 'none');
        $('.child').animate({
            opacity: 0
        });
        hovS = 0;
    }
    $('.console').append(hovS + ' - ');
});

jsfiddle code here


Solution

  • It seems like you are making this way harder than you have to with all the css changes... since you are using jquery why not just do something like this?

    JSFiddle

    $(".parent").hover( function() {
        $(".child").fadeIn();
    }, function() {
        $(".child").fadeOut();
    });
    

    Also since these are classes it implies there could be multiple parents and children... you might want to change the child selector to something like $(this).find(".child")...


    If you really need the console thing...

    JSFiddle

    $(".parent").hover( function() {
        $(this).find(".child").fadeIn();
        $(".console").append("1 - ");
    }, function() {
        $(this).find(".child").fadeOut();
        $(".console").append("0 - ");
    });