Ad

How To Add Behaviour (onclick) On In A Tag Which Has Different Behaviour (onclick)?

- 1 answer

I have a data table which has a span element in every row. When someone clicks on the <tr> element JS code is executed. When someone clicks on the <span> element another JS code is execute. The problem is that often it detects the click on the <tr> even though I click on the <span> element.

Is there any javascript/jquery function which helps me out?

HTML Code

<table class="table">
  <thead>
    <tr>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr class="behaviourTr">
      <td></td>
      <td></td>
      <td></td>
      <td><span class="glyphicon glyphicon-pencil"></span>
      </td>
    </tr>
  </tbody>
</table>

JS Code

$('.behaviourTr').on('click', function() { ... });
$('.glyphicon-pencil').on('click', function() { ... });
Ad

Answer

When you click on the span element, you are technically still clicking on the tr element as well (because the span is a descendant element and the event bubbles up to the tr element).

Inside of the tr click event listener, you could check event.target (which is the clicked element) to see if the span element wasn't clicked. In the snippet below, the is() method is used to determine if event.target is not a span element.

See this example.

$('.behaviourTr').on('click', function(e) {
  if (!$(e.target).is('span')) {
    // The tr was clicked, but the span wasn't
  }
});
Ad
source: stackoverflow.com
Ad