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);
}
1

3 Answers 3

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();
});  
Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

Wow,what a nice way to handle this sort of stuff.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.