javascriptevent-handlingdom-eventsonfocus

How to set focus at an input element without dispatching the 'focus' event?


Following example code is provided in order to introduce the matter ...

const elm = document.getElementById('fname');

elm.addEventListener('focus', evt =>
  console.log(
    `input element focused, event.type: "${ evt.type }"`
  )
);

elm.focus();
<input type="text" id="fname" name="fname">

As one can see, the 'focus' event gets dispatched. But I wish to focus the input element without dispatching this event.

Can this be done. And how would one achieve such behavior?


Solution

  • The OP could register an initial 'focus' listener where the handler function's sole purpose is to immediately stop the passed event's propagation ... evt.stopImmediatePropagation(). The downside is that no other handler of any later registered 'focus' listener can be executed.

    The proposed "initial" 'focus' listener code ...

    elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );
    

    const elm = document.getElementById('fname');
    
    // the "initial" listener subscription prevents execution of ...
    elm.addEventListener('focus', evt =>
      evt.stopImmediatePropagation()
    );
    
    // ... other handler functionality which got registered later.
    elm.addEventListener('focus', evt =>
      console.log(
        `input element focused, event.type: "${ evt.type }"`
      )
    );
    elm.focus();
    <input type="text" id="fname" name="fname">