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.
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.
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">
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)
}
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
}
}