0

I have a page with 5 input fields. How do I add a blur event listener on them together?

I get an error when I try

document.querySelectorAll('input').addEventListener('blur', e => {
  console.log('blur on input')
})

EDIT 1

I am able to add eventListeners to individual items like so,

const allInputs = [...document.getElementsByTagName('input')]
allInputs.forEach(item => item.addEventListener('blur', (e) => console.log('blur') ))

But is there a way to add a collective event listener on HTMLCollection?

Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
rodiwa
  • 1,690
  • 2
  • 17
  • 35

2 Answers2

0

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

You have to loop through all the elements to attach the event (blur) individually like the following way:

document.querySelectorAll('input').forEach(function(el){
   el.addEventListener('blur', e => {
      console.log('blur on input')
   });
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

This will work. Adding a event listener to document and capturing the target when the event bubbles.

document.addEventListener("focusout",function(event){
    if(event.target instanceof HTMLInputElement) //can also be used as elem.target.tagName.toLowerCase()=="input"
    {
        console.log("Using focusout : "+event.target.id);
        event.preventDefault();
    }
});
document.addEventListener("blur",function(event){
    if(event.target instanceof HTMLInputElement) //can also be used as elem.target.tagName.toLowerCase()=="input"
    {
        console.log("Using blur : "+event.target.id);
        event.preventDefault();
    }
},true);
<input id="1">
<input id="2">
<input id="3">
<input id="4">
<input id="5">

true in the blur event is to make it bubble.

MDN Docs for blur event, focusout event

Refer this nice article for more info.

Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42