Fi3n1k
Fi3n1k

Reputation: 891

Avoid onclick from parent

Is there a way for the following sample:

<tr id="x" onclick="do_something()">
    <td>Lorem ipsum</td>
    <td>Lorem ipsum</td>
    <td>Lorem ipsum</td>
    <td>
       <a href="javascript:;" onclick="do_something_else()">CANCEL</a>
    </td>
</tr>

when clicking CANCEL link not to execute both do_something() and do_something_else().

I only need to execute do_something_else()

Thank you

Upvotes: 1

Views: 38

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Two options for you:

  • The Minimum Change

  • The Modern Way

The Minimum Change

In the onXYZ attribute, your code is effectively within a function that has an event variable (directly on most browsers, a global on older IE), so if you pass that into your function, you can call stopPropagation on it (if it has that function) or use cancelBubble if it doesn't (old IE):

function do_something() {
  snippet.log("do_something called");
}
function do_something_else(event) {
  snippet.log("do_something_else called");
  if (event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  }
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<table>
  <tbody>
    <tr id="x" onclick="do_something()">
      <td>Lorem ipsum</td>
      <td>Lorem ipsum</td>
      <td>Lorem ipsum</td>
      <td>
        <a href="javascript:;" onclick="do_something_else(event)">CANCEL</a>
      </td>
    </tr>
  </tbody>
</table>

The Modern Way

Using onXYZ attributes is fairly old-fashioned these days. Instead, consider hooking up your handlers in a modern way, which gives you the stopPropagation() function:

var x = document.getElementById("x");
x.addEventListener("click", do_something, false);
x.querySelector("a").addEventListener("click", function(e) {
  e.stopPropagation();
  do_something_else();
}, false);

function do_something() {
  snippet.log("do_something called");
}
function do_something_else() {
  snippet.log("do_something_else called");
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<table>
  <tbody>
    <tr id="x">
      <td>Lorem ipsum</td>
      <td>Lorem ipsum</td>
      <td>Lorem ipsum</td>
      <td>
        <a href="javascript:;">CANCEL</a>
      </td>
    </tr>
  </tbody>
</table>

If you need to support IE8, this answer gives you a function to handle the fact that IE8 doesn't support addEventListener (but does have its Microsoft-specific predecessor, attachEvent).

Upvotes: 2

Related Questions