skip to Main Content
function focusInputFunction(event){
  console.log("focus");
  event.stopPropagation();
  event.stopImmediatePropagation();
}

function clickTr(){
  console.log("tr");
}
<table>
  <tr onclick="clickTr()">
    <td>
      <input id="myInput" onfocus="focusInputFunction(event)"type="text">
    </td>
  </tr>
</table>

I want that when I focus on my text field, the event click on the <tr> element is not executed.

I just want to execute the focus event on my text field and not fire the click event on the <tr>.

How can I do this?

2

Answers


  1. You can try using a flag variable and return from the function clickTr based on value like the following way:

    let isFocusEvent = false;
    
    function focusInputFunction() {
      console.log("focus");
      isFocusEvent = true;
    }
    
    function clickTr() {
      if (isFocusEvent) {
        isFocusEvent = false;
        return;
      }
      console.log("tr");
    }
    <table>
      <tr onclick="clickTr()">
        <td>
          <input id="myInput" onfocus="focusInputFunction(event)"type="text">
        </td>
      </tr>
    </table>
    Login or Signup to reply.
  2. event.stopPropagation(); only stops the propogation to parent for the focus event. the click event will still be fired. Add it to click event on input. Check code below.

    function focusInputFunction(event) {
      console.log("focus");
      event.stopPropagation();
    }
    
    function clickTr() {
      console.log("tr");
    }
    
    function clickinput(event) {
      event.stopPropagation()
    }
    <table>
      <tr onclick="clickTr()">
        <td>
          <input id="myInput" onclick="clickinput(event)" onfocus="focusInputFunction(event)" type="text">
        </td>
      </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search