Scott Yu - builds stuff
Scott Yu - builds stuff

Reputation: 11763

Clickable parent DIV to show and hide children DIV has problems in jQuery

This is kind of crazy and I am not sure what's wrong. I want to make a DIV clickable to show/hide children divs. But once I do a hide of one children, I cannot unhide it.

Here's my entire code. Any help appreciated. IN example below, I cannot unhide inner1 when clicking Cancel button.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>

<div class="wrapper">
    <div class="inner1">
    1
    </div>

    <div class="inner2" style='display:none'>
    2 <input type='button' value='cancel' class='cancel'>
    </div>

</div>


<style>
div {border:1px solid red;}
</style>

<script>
$(document).ready(function() { 
        $('.wrapper').live("click", function(){
            $('.inner1').hide();
            $('.inner2').show();
        });


        $('.cancel').live("click", function(){
            $('.inner1').show();
            $('.inner2').hide();
        });
});
</script>

Upvotes: 0

Views: 962

Answers (1)

Nick Craver
Nick Craver

Reputation: 630559

You need to stop the click on .cancel from bubbling up and also being a click on .wrapper by using .stopPropagation(), like this:

$('.cancel').live("click", function(e){
  $('.inner1').show();
  $('.inner2').hide();
  e.stopPropagation();
});

You can test it out here. What's currently happening is you are hiding it, but then the .wrapper click handler gets the click and immediately shows .inner2 again.

Upvotes: 1

Related Questions