0

I have the following JavaScript:

<div>
    <tr onClick="click1()">
        <td>
            click 1
        </td>
        <td onClick="click2()">
            click 2
        </td>
    </tr>
</div>

function click1() {
  alert(1);
}

function click2() {
  alert(2);
}
<table border="1">
  <tr onClick="click1()">
    <td>
      click 1
    </td>
    <td onClick="click2()">
      click 2
    </td>
  </tr>
</table>

If I click 'click 1', the click1() function is called as expected. If I click 'click 2', the click1() & click2() functions are both called.

Question

How do I make the click on 'click 2' only call the click2() function, and not call the click1() function?

4
  • put the onClick attribute into the td tag of click 1 Commented Oct 21, 2021 at 11:03
  • Add event.stopPropagation(); in your click2 function. Commented Oct 21, 2021 at 11:06
  • The fact that there are two different "answers" to this question hints at the fact it should be closed as it does not show any research effort. Commented Oct 21, 2021 at 11:07
  • @noah1400, thanks for your reply. I cannot, because what I am trying to achieve is if the user click on the row, it calls function click1(). However, if they click on a specific item in the row it calls function click2(). Commented Oct 21, 2021 at 11:07

1 Answer 1

1

Well, the easiest way is just to move your 'click 1' trigger to the button itself:

<div>
    <tr>
        <td onClick="click1()">
            click 1
        </td>
        <td onClick="click2();">
            click 2
        </td>
    </tr>
</div>

However, I'm assuming you want to keep the click 1 trigger where it is, in which case you can add event.stopPropagation() to the event:

<div>
   <tr onClick="click1();">
       <td>
           click 1
       </td>
       <td onClick="click2(); event.stopPropagation();">
           click 2
       </td>
   </tr>
</div>
Sign up to request clarification or add additional context in comments.

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.