2

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

FranticJ3
  • 107
  • 1
  • 12

3 Answers3

6

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

GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
0

Here's an updated fiddle with the problem resolved: https://jsfiddle.net/6u39dfxd/1/

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

$('#parent').click(function(event) {
    if($(this).has(event.target).length === 0) {
        $('#child').toggleClass('display');
    }
});

Basically, you get the event.target on click and ensure that it's not contained within the parent element. You could get more specific if there's more than one child, but this should resolve it.

ghost_dad
  • 1,308
  • 2
  • 12
  • 21
0
  $('#clickMe').click(function() 
  { 
      $('#child').toggle();
  }); 

  $('#parent').click(function(e)
  {
    $('#child').toggle();      
  });
    $("#parent").children().click( function(e) {
    e.stopPropagation();
  });

I think this will solve your problem.

Chanchal Zoarder
  • 107
  • 1
  • 14