Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  130] [ 4]  / answers: 1 / hits: 98792  / 9 Years ago, fri, september 4, 2015, 12:00:00

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.


More From » javascript

 Answers
30

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>

[#65182] Wednesday, September 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
talonb

Total Points: 596
Total Questions: 103
Total Answers: 91

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;