13

I have

  • table row with click event
  • button with click event, that button is on table row

and I have problem. When I hit button, row click event execute too, but I don't want this behavior. I want only button click execute, without row click.

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
MicTech
  • 42,457
  • 14
  • 62
  • 79

5 Answers5

11

Using jQuery (due to question tag):

$('#yourButton').click(function(e) {
    // stop event from bubbling up to row element
    e.stopPropagation();

    // now do your stuff
});
stpe
  • 3,611
  • 3
  • 31
  • 38
8

look at your code this is what you should do in the button click event stopPropagation

andres descalzo
  • 14,887
  • 13
  • 64
  • 115
3

You can call an extra function onClick

this is the function:

function cancelBubble(e){

    e.cancelBubble = true;
    if(e.stopPropagation)
     e.stopPropagation();
}

And button's onClick you can write like

onclick="yourfunctionname();cancelBubble(event)"

yourfunctionname:: is the name of your function you are already calling.

VVV
  • 7,563
  • 3
  • 34
  • 55
user160820
  • 14,866
  • 22
  • 67
  • 94
1

Also I had a dropdown overlayed on a clickable element. So just use the following to prevent propagation to the underlying element for all modern browsers

onclick="yourfunctiontohandle();event.stopPropagation();"

For older cross browser solution, must use IE event.cancelBubble

onclick="if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble=true;"
Vin
  • 11
  • 2
0

Since global event is deprecated, if someone wants to do with plain javascript here is the way to stop propagation

document.querySelector("#outer").addEventListener('click', e => {console.log('Outer div clicked')});
document.querySelector("#inner").addEventListener('click', e => {console.log('Inner div clicked'); e.stopPropagation()});
<div id="outer" style="width: 100px; height: 100px; background-color: red; display: flex; justify-content: center; align-items: center;">
    <div id="inner" style="background-color: black; width: 50px; height: 50px;"></div>
</div>

Click on the red and black squares to see the result

Bharat
  • 1,044
  • 15
  • 34