Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop propagating event from parent div to child div

Tags:

html

jquery

dom

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

like image 432
Rahul Chakrabarty Avatar asked Jan 29 '15 08:01

Rahul Chakrabarty


People also ask

How do you stop event propagation from parent to child?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do you stop event propagation?

Event.stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.

How do I prevent a parent's onclick event from firing when a child is clicked?

If you use event. stopPropagation() , sure it will stop any parent events from firing.

How do you stop event propagation in typescript?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.


2 Answers

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

if( event.target !== this ) {
       return;
}
//...do stuff.. 
like image 190
iurii_n Avatar answered Oct 14 '22 13:10

iurii_n


A more elegant solution is to use CSS and disable the pointer events on the children.

#categoryList * {
    pointer-events: none;
}

Or in your specific case to have no events on the listed-category element:

#listed-category {
    pointer-events: none;
}
like image 25
Avatar Avatar answered Oct 14 '22 11:10

Avatar