0

Here's my snippet.

Is there any other way other than appending event listener to every element of the class?
I would like to avoid loops if possible.

Vikrant
  • 4,920
  • 17
  • 48
  • 72
phoxd
  • 1,546
  • 3
  • 12
  • 26

3 Answers3

1

Use [].forEach.call() to iterate HTMLCollection

var user_input = document.getElementsByClassName('inp');
[].forEach.call(user_input, function(el) {
  el.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode == 13) {
      console.log(this.value); //this keyword in the handler function refers to element on which event is invoked!
    }
  });
});
<input type="text" class="inp">
<input type="text" class="inp">
<input type="text" class="inp">
Community
  • 1
  • 1
Mandeep Singh
  • 1,287
  • 14
  • 34
1

You could attach a single listener to a parent element (in this case <body>) and use the event.target attribute to get the DOM node that the event fired off.

This works because the event bubbles up through the DOM hierarchy. It's called "Event Delegation"

See these links:

Example Code:

HTML:

<div id="parent">  
    <input type="text" class="inp">
    <input type="text" class="inp">
    <input type="text" class="inp">
</div>

JavaScript:

document.getElementById("parent").addEventListener("keyup", function (event) {
    console.log(event.target.value)
}
Jason Cemra
  • 563
  • 5
  • 15
1

I couldn't add comment to Jason Cemra.

In addition to His/Her answer the target element as required by PhoxKiD is the input with the class 'inp'. So place a condition

document.getElementById("parent").addEventListener("keyup", function (event){
    if(event.target.className == 'inp') {
        //your code
    }
    else{  //for other inner elements
        event.preventDefault(); //prevents the default action
        event.stopPropagation(); //stop bubbling up
    }
}
Bishwa
  • 56
  • 2
  • As requested by PhoxKiD, Jason Cemra's approach is without loop/iteration – Bishwa Oct 07 '16 at 07:21
  • Great! btw what does bubbling mean? – phoxd Oct 07 '16 at 07:23
  • 1
    When an event is triggered from an object it bubbles (passes) up towards the object's parent. In the Jason Cemra's answer the event is triggered from the input object and that event bubbles up and handled by its parent. Here in the above code if the event is not triggered from the input with the classname 'inp' the 'event.stopPropagation();' kills the event or pops the bubble out preventing it from further bubbling up. – Bishwa Oct 11 '16 at 07:35