To try and simplify event delegation and answer the question with an example using it.
Events fired by elements like <input>
"bubble up" the DOM. Now, you can either catch an event on the element that fired it by attaching a listener to it or you can attach a listener to a parent element which will catch it when the event reaches it.
This is known as "event delegation" because you're delegating the catching of an event to a parent element that didn't fire it. And this is useful because you can group child elements together and have their parent element listen for those events as they bubble up to meet it. For example you can attach a listener to a containing <form>
element to catch all of the events from its child input and button elements.
In this example I've used a <fieldset>
as a parent container, and attached one input
listener to it. When the input
event is fired on any of its children they bubble up and get caught in that listener. From there you can check to see what element fired the event, and then write some code to handle it. Here we're adding the value of the input element to the text content of its sibling output element.
(Because I wasn't sure what your code was meant to do in this example I've just made the input value appear as text content in the <div class="output">
elements.)
// Cache the fieldset element, and attach
// a listener to it. This listener will catch the
// events from its child elements as they "bubble up" the DOM
const fieldset = document.querySelector('fieldset');
fieldset.addEventListener('input', handleChange);
// Our event handler - note that we're passing in
// the event (`e`) as an argument
function handleChange(e) {
// First the handler needs to check that the
// child element that fired the event (the event target)
// is one of the input elements
if (e.target.closest('input')) {
// We then assign the output element (the input element's
// `nextElementSibling`) to an `output` variable,
// and assign the event target's value to its textContent
const output = e.target.nextElementSibling;
output.textContent = e.target.value;
}
}
fieldset > .container ~ .container { margin-top: 0.5rem; }
.container { display: flex;}
label { width: 12vw; }
input { width: 40vw; }
.output{ margin-left: 1rem; }
<fieldset>
<legend>Measures</legend>
<div class="container">
<label for="measure1">One</label>
<input maxlength="10" maxsize="10" type="text" id="measure1">
<div class="output"></div>
</div>
<div class="container">
<label for="measure2">Two</label>
<input maxlength="10" maxsize="10" type="text" id="measure2">
<div class="output"></div>
</div>
</fieldset>
Additional documentation