dewd
dewd

Reputation: 4429

jquery parent hide not working

Take this jsfiddle. If you click the blue square, a red square will appear with a purple child square (apologies if you're colour-blind):

    $('#holder').click(function(){
        $(this).children('.parent').show();
    });

This works fine. When you click the purple child square, the red parent square should get hidden:

    $('.child').click(function(){
        $(this).parent().hide();
        console.log($(this).parent().css('display'));
    });

This doesn't work, despite the console returning a css value of display:none for the parent element. I wonder if anyone could explain why the parent doesn't get hidden, and what alternatives there might be to hide it?

HTML

<div id="holder">
    <div class="parent">
        <div class="child">

        </div>
    </div>
</div>

CSS

#holder {
    height: 50px;
    width:50px;
    background-color: blue
}
.parent {
    position:fixed;
    top:100px;
    left:200px;
    display:none;
    width:200px;
    height:200px;
    background-color:red
}
.child {
    position:absolute;
    width:50px;
    height:50px;
    background-color:purple
}

JS

$(function(){
    $('#holder').click(function(){
        $(this).children('.parent').show();
    });
    $('.child').click(function(){
        $(this).parent().hide();
        console.log($(this).parent().css('display'));
    });

});

Upvotes: 1

Views: 2554

Answers (4)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

Use $(this).closest('div.parent').hide()

Upvotes: -2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

The problem you have is that just after you hide the element, the event propagates to #holder, which is a parent of the .parent element and thus the event handler you defined on #holder shows the element again.

Add return false at the end of your event handler to prevent propagation :

    $('.child').click(function(){
        $(this).closest('.parent').hide();
        console.log($(this).parent().css('display'));
        return false;
    });

Demonstration

Upvotes: 8

Chad
Chad

Reputation: 5408

You could use stopPropagation, which will stop other events from occurring while you're clicking.

$(function(){
    $('#holder').click(function(){
        $(this).children('.parent').show();
    });
    $('.child').click(function(e){
        e.stopPropagation();
        $(this).parent().hide();
    });        
});

You can see it here: http://jsfiddle.net/BS6Es/2/

Upvotes: 1

Mr. B.
Mr. B.

Reputation: 8697

fiddle: http://jsfiddle.net/BS6Es/1/

$(function(){
    $('#holder').click(function(){
        $(this).children('.parent').show();
    });
    $('.child').click(function(e){
       $(this).parent().hide();
       return false;    // important!        
    });        
});

You've to return false. Have fun!

Update: as already mentioned, you can use closest()instead of parent().

Upvotes: 1

Related Questions