FranticJ3 FranticJ3 - 1 year ago 78
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:


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


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

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

And here is the jQuery:


if($('#child').data('clicked') == true )
// do nothing
} else

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 Source

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

  $('#parent').click(function() {
  $('#child').click(function(e) {

More information can be found here

Updated Fiddle