viv
viv

Reputation: 299

Hiding parent divs in Jquery

I am having a simple div structure ( see below ). All I am trying to do is when the div id "interviewer-Button" is clicked the following div's should appear and when the div id "elt" is clicked divs from id "parent0" till the end should hide.

The display part works fine. However, when I try to hide, it just does NOT hide. When i click on the div id "elt" the alert message "hh" (see below) gets thrown!! Weird. Any help on how to hide this?

<div id = "interviewer-Button">
   Interviewer
   <div id = "parent0">
         Viv
          <div id = "parent1">
                Parent
                <div id = "elt">
                     Close
                 </div>

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


<script>
$(document).ready(function() {
    $("#parent0").hide();   
    $("#interviewer-Button").click(function() { alert("hh");$("#parent0").show(); });
    $("#elt").click( function () {
            $(this).parent().parent().hide();
         });                
     });
</script>

Upvotes: 9

Views: 34056

Answers (3)

Cezary Daniel Nowak
Cezary Daniel Nowak

Reputation: 1174

You can also take advantage of event propagation and attach just one event:

$(function() {
  $("#parent0").hide(); 
  $("#interviewer-Button").on('click', function(e){
    $(this).find('#parent0').toggle(e.target.id !== 'elt');
  });
});

Upvotes: 0

Stephen Smith
Stephen Smith

Reputation: 99

n/aUsed a combination of the above. Thanks to both members for their answers. great help.

            jQuery(function ($) {
                $('.coffee-strength p span').each(function () {
                    var string = $.trim($(this).text());
                    if(string!="22"){
                        $(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />');
                    }else{
                        $(this).parent().parent().hide();    
                    }
                    });

            });

            </script>

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532465

You need to stop propagation of the click event in the handler for the inner element. Without that the handler for the parent will also be invoked. See the jQuery event object for more info.

$("#elt").click( function (e) {
    e.stopPropagation();
    $(this).parent().parent().hide();
});

Upvotes: 26

Related Questions