Home > Blockchain >  Access EventTarget of addEventListener without using a variable
Access EventTarget of addEventListener without using a variable

Time:05-08

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:

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

(And of course, I don't mean

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

)

CodePudding user response:

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>

CodePudding user response:

You can do it with event.target from function params

document.querySelector('select').addEventListener('focus', (event) => {
  event.target.blur();
});
<select name="cars" id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

  • Related