CodeJoe
CodeJoe

Reputation: 260

Add events (eg. blur) to multiple <input/> elements (present and future)

Case:

On site (let's say it's to-do list) there are multiple <input class="awesome-input" type="text"/> elements. There is also possibility to add next inputs with the same class.

HTML example:

<button class="add-input">Add new awesome input</button>
<div class="inputs-container">
   <input class="awesome-input" type="text"/>
   <input class="awesome-input" type="text"/>
   <input class="awesome-input" type="text"/>
</div>

Question:

Is it possible to add input events (e.g. blur) to multiple elements (pure Javascript)? To already existing and for created in future also.

Upvotes: 1

Views: 888

Answers (1)

vrintle
vrintle

Reputation: 5586

You can use Array.map() to traverse through an array of inputs, tagging them with a blur event.

And, when a new input is added you can do the same thing there also.

window.onload = function() {
  var inputs = Array.from(document.querySelectorAll('input.awesome-input'));
  var button = document.querySelector('button');
  
  function blurHandler(elem) {
    elem.style.border = '2px solid #DDD'; // just an example
  }
  
  inputs.map( input => input.addEventListener('blur', event => blurHandler(event.target)) );
  
  button.addEventListener('click', function() {
    var input = document.createElement('input');
    
    input.addEventListener('blur', event => blurHandler(event.target));
    
    input.className += ' awesome-input';
    document.querySelector('.inputs-container').appendChild(input);
  });
}
<button class="add-input">Add new awesome input</button>
<div class="inputs-container">
   <input class="awesome-input" type="text"/>
   <input class="awesome-input" type="text"/>
   <input class="awesome-input" type="text"/>
</div>

Upvotes: 2

Related Questions