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

Time:12-01

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?

CodePudding user response:

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">

CodePudding user response:

I'm not a JS expert. And if you remove the listener event from the input? Even so, you can focus it but there will no longer be any event that is activated.

but this may not work as you expect

I took the example from here: removeEventListener() I hope works for you!!!

const body = document.querySelector('body')
const btn = document.getElementById('btn');  
const el = document.getElementById('fname');
let toggle = false;

function makeBackgroundYellow() {
    console.log("input focus");
    body.style.backgroundColor = toggle ? 'white' : 'yellow';
    toggle = !toggle;
}; 

el.addEventListener('focus', makeBackgroundYellow);
btn.addEventListener('click', ()=>{
    el.removeEventListener("focus", makeBackgroundYellow, false);  
});
<input type="text" id="fname" name="fname">
<button id="btn">Press</button>

CodePudding user response:

The autofocus global attribute is a Boolean attribute indicating that an element should be focused on page load, or when the that it is part of is displayed.

<input type="text" id="fname" name="fname" autofocus>

MDN Docs

  • Related