How to stop propagating event from parent div to child div

I want to stop propagate event from parent div to child div in my html. Here a simple code what I’m trying to do:

<div>
  <div id='categoryList'>
    <div class='listed-category'>
      <span>some content</span>
      <a id='close'>x</a> //"a" is used to remove the div
    </div>
  </div>
</div>
<div id='dropdown'>
</div>

In the above code if I click on <div id='categoryList'> the <div id='dropdown'> will slide-up and down by bellow code.

$(document).ready(function () {

    $('#categoryList').click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        if ($('#dropdown').is(":visible")) {
            $('#dropdown').slideUp(400);
        }
        else {
            $('#dropdown').slideDown(400);
        }
    });
})

But when I click on the child <div class='listed-category'> the above JavaScript executes and the <div id='dropdown'> is sliding up and down. How to stop this? Yet I want to be able to click on <a id='close'> to remove the child div

Answer

Check target for match clicked object. Try this code in beginning of click event handler.

if( event.target !== this ) {
       return;
}
//...do stuff.. 

Leave a Reply

Your email address will not be published. Required fields are marked *