Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event onclick on <td> and <tr>

Tags:

javascript

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.

like image 876
delphirules Avatar asked Sep 04 '15 18:09

delphirules


2 Answers

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>
like image 61
Spencer Wieczorek Avatar answered Oct 31 '22 00:10

Spencer Wieczorek


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>
like image 6
Hacketo Avatar answered Oct 30 '22 22:10

Hacketo