FranticJ3 FranticJ3 - 6 months ago 32
Javascript Question

jQuery: When parent element is clicked, hide child element. When child element is clicked, don't hide it

I have a parent element with a child element that is displayed/hidden by clicking a specific button on the page. The button just changes the style from display:none to display:block, pretty simple. The child element starts off as display:none;

I want to hide this element when the parent element is clicked, but not when the child element is clicked, which is problematic since the child element is apart of the parent element.

I saw that there was data(); that can check if an element was clicked, but that doesn't seem to be working.

Here is the html:

<style>

#parent {width:200px;height:200px;}
#child {display:none;width:50px;height:50px;}
#child.display {display:block;}

</style>

<div id="parent">
Some content
<div id="child">Some other content</div>
</div>

<button id="clickMe">Toggle Child</button>


And here is the jQuery:

$(function()
{
$('#clickMe').click(function()
{
$('#child').toggleClass('display');
});

$('#parent').click(function()
{
if($('#child').data('clicked') == true )
{
// do nothing
} else
{
$('#child').toggleClass('display');
}
});
});


For the sake of this example I hid the child element by default. Don't worry, I won't be doing that in production. I'm just working on figuring out how to do this base functionality.

Here is a link to demo of it: jsfiddle

Answer

You can accomplish that by binding an event to the child and stop the propagation.

  $('#parent').click(function() {
     $('#child').toggleClass('display');
  });
  $('#child').click(function(e) {
     e.stopPropagation();
  });

More information can be found here

Updated Fiddle