0

I have the following div and click listeners:

  $('.right-col .modal-container').live('click',function(e) {
       $(this).remove();
       $('.right-col .modal-backdrop').remove();
  });


<div class="modal-container">
    ....some other buttons and html elements inside
</div>

The issue is that when ever I click on a button inside this modal-container element, it would also trigger the click function at .modal-container. How do I avoid this cascading?

adit
  • 32,574
  • 72
  • 229
  • 373
  • 2
    https://www.google.com.au/search?q=prevent+click+from+propagating&oq=prevent+click+from+propagating&aqs=chrome..69i57j0j69i60.554j0j1&sourceid=chrome&ie=UTF-8 – Marty Sep 11 '13 at 04:13
  • 1
    live is deprecated and removed from up 1.9+ – epascarello Sep 11 '13 at 04:14

3 Answers3

1

how do I make sure that this click event doesn't come from a propagated click, but a direct click on this div

Use if (this == e.target){

$('.right-col .modal-container').on('click',function(e) {
    if (this == e.target){
       $(this).remove();
       $('.right-col .modal-backdrop').remove();
    }
});

e.target is the element that you clicked directly as opposed to e.currentTarget which is the current element in the propagation. This will work also in case of event capturing because with event capturing: the event is fired on the container first before reaching the clicked element.

For performance benefit, you should also try stopPropagation as suggested by @Karl-André Gagnon to stop event propagation in case of event bubbling

Difference between event capturing and event bubbling

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
0

After writing your question title in google, here the first link : http://api.jquery.com/event.stopPropagation/

And here how to use it :

$('.right-col .modal-container').on('click',function(e) {
    $(this).remove();
    $('.right-col .modal-backdrop').remove();
}).find('button').click(function(e){ //guessing you have a <button> in the div
     e.stopPropagation();
});
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • what if the question was the other way around, how do I make sure that this click event doesn't come from a propagated click, but a direct click on this div – adit Sep 11 '13 at 04:20
0

If you don't want the div.modal-container to be the target, you can register the click event on the <button> instead. Assuming you'd have a class name for the button as .modal-container, you can try this:

$("button.modal-container").live('click', function(e){
    // your button specific actions here
    // ...

    $(e.target).parents(".modal-container").first().remove();
});
Vineeth Pradhan
  • 8,201
  • 7
  • 33
  • 34