0

How can i make sure that onclick events only fires by clicking on td not on the span ?

<td style="cursor: pointer;" onclick="getDetails(13,3)">
   <span class="responsiveExpander"></span>
    TEST
</td>


function getDetails(table_id,id)
{
   alert(table_id + id);
}
Khirad Zahra
  • 843
  • 2
  • 17
  • 42

3 Answers3

3

You have to add an event listener to the inner child and cancel the propagation of the event.

In plain JS something like

document.getElementById('inner').addEventListner('click',function (e){
   e.stopPropagation();
});

is sufficient. Note that jQuery provides the same facility:

$(".inner-div").click(function(event){
    event.stopPropagation();
});  

or

$(".inner-inner").on('click',function(event){
    event.stopPropagation();
});  
Jonas
  • 2,139
  • 17
  • 38
2

Assuming you want to prevent clicks on all sub-elements, pass the event to getDetails and have it see if event.currentTarget is the same as event.target.

function getDetails(event, table_id, id) {
   if (event.currentTarget !== event.target) {
     return; // clicked a sub-element
   }
   alert(table_id + id);
}
span {
 color: red;
}
<table>
<tr>
<td style="cursor: pointer;" onclick="getDetails(event, 13,3)">
   <span class="responsiveExpander">SHOULD NOT ALERT</span>
    TEST
</td>
</tr>
</table>
spanky
  • 2,768
  • 8
  • 9
0

You may do as follows;

data.addEventListener("click", function(e){
                                 e.target === this && console.log("td clicked");
                               });
td {border: red solid 2px;}
span{color: white; background-color: black}
<table>
  <tr>
    <td id="data" style="cursor: pointer">
      <span>SPAN:</span> TEST
    </td>
  </tr>
</table>
Redu
  • 25,060
  • 6
  • 56
  • 76