Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access EventTarget of addEventListener without using a variable

This codes removes the focus from the select element after you click it:

const select = document.querySelector('select');
select.addEventListener('focus', () => {
  select.blur();
});
<select>
  <option>Option 1</option>
  <option>Option 2</option>
</select>

Is it possible to change it so that it won’t be necessary to assign a constant/variable first?

Something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// pseudocode
document.querySelector('select').addEventListener('focus', () => {
  EventTarget.blur();
});

(And of course, I don’t mean

document.querySelector('select').addEventListener('focus', () => {
  document.querySelector('select').blur();
});

)

>Solution :

yes it is possible. just modify your code a bit.

document.querySelector('select').addEventListener('focus', (e) => {
  e.target.blur();
});
<select>
  <option>Option 1</option>
  <option>Option 2</option>
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading