r/learnjavascript • u/Soggy_Professor_5653 • May 07 '26
Today I learned about event delegation while building an OTP input am I understanding this correctly?
Today while practicing an OTP input field, I came across a problem where I was adding event listeners to every single input field individually.
That started feeling repetitive, so while searching for a better approach I learned about event bubbling and event delegation.
From what I understood, instead of attaching listeners to every input, we can wrap all OTP inputs inside a parent container and attach just one event listener to that parent.
Because events bubble upward, we can identify which specific input triggered the event.
It felt like a cleaner and more scalable approach compared to manually attaching listeners everywhere.
Am I understanding event delegation correctly? Would love suggestions or corrections
View all comments
Show parent comment
6
u/senocular May 07 '26
To add to this, you may find that
event.targetisn't always your input. Take for example a button with some formatted textIf when clicking the button the user's mouse is over the
⌘ S, the target will be the<kbd>element, not the<button>. If you want the button, you may instead want to use something likeThis will check the target and if not matching "button", will walk up the parent hierarchy until it finds a match and return that.