Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.stopPropagation() is not working as expected?

I have a simple table :

enter image description here

The TR has <tr onclick='alert("row");'>

And the button has :

$("body").on('click',".b",function (e){
  alert('button');
  e.stopPropagation();
});

However - Although I wrote e.stopPropagation(); it still alerts : "row , button".

Now , I know that the event handler is attached to the body and the selector is checked against it ( the click start at the button and move up to the body , just like $.live use to do but against document...).

But the checking should be for the button click and not for the TR click.

It seems that while i'm clicking , it propagates to the "body" ( because I attached event handler to it) and while its way up to the body it activates the click on the TR.

What is going on here? How can I keep my code ( attach to body) and still have only alert of "button".

P.s.

I know I can simply do :

$(".b").on('click',function (e){
  alert('button');
  e.stopPropagation();

});

but I want to know why my current(!) code doesnt work.

like image 526
Royi Namir Avatar asked Jun 10 '13 10:06

Royi Namir


1 Answers

The problem is that you're attaching the event handler to the body, even if it delegates to the .b element. This event handler is called only after the tr event handler is called, so it's too late to stop propagation.

As I suppose you want to deal with dynamically added elements and can't simply bind the event handler to the td, I can suggest you this :

$('body').on('click',"tr",function (e){
  alert('row');
});
$("body").on('click',".b",function (e){
  alert('button');
  e.stopPropagation();
});

Demonstration

like image 64
Denys Séguret Avatar answered Sep 18 '22 09:09

Denys Séguret