I have an onclick event in a table both on a <td>
and <tr>
elements. I need when the user clicks on the specific column (<td>
), the <tr>
event won't be triggered, only the <td>
one.
How to do it ?
Example :
HTML :
<tr onclick='trclick();'>
<td>Column 1</td>
<td>Column 2</td>
<td onclick='tdclick();'>Column 3</td>
</tr>
JS :
function trclick(){console.log('tr clicked')};
function tdclick(){console.log('td clicked')};
When the user clicks on 'Column 3', both events are triggered, but i want only tdclick()
to be triggered.
What you need to do is to stop the propagation of the parent event when a child is clicked, it's easy done in jQuery, but naively you need to do a little more work:
function trclick(){
console.log('tr clicked')
};
function tdclick(e){
if (!e) var e = window.event; // Get the window event
e.cancelBubble = true; // IE Stop propagation
if (e.stopPropagation) e.stopPropagation(); // Other Broswers
console.log('td clicked');
};
Note, for Firefox you need to pass a event
parameter:
<td onclick='tdclick(event)'>Column 3</td>
You need to stop the propagation of the event.
to access the event object you need to use it as parameter of your function tdclick
function trclick(){console.log('tr clicked')};
function tdclick(event){
console.log('td clicked');
event.stopPropagation()
};
<table><tbody>
<tr onclick='trclick();'>
<td>Column 1</td>
<td>Column 2</td>
<td onclick='tdclick(event);'>Column 3</td>
</tr>
</tbody></table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With