Coming from React it's easy to fall into the trap. But let's understand some events the browser fires when one interacts with the input tag
- onfocus - Fired when the user sets focus on the element
- onblur - Opposite of onfocus. Fired when an element loses focus
- onchange - (the most interesting one 😅). Unlike React, the browser fires onchange event after focus from input element is taken off. So when focus is set on an input element and something is typed, onchange won't be fired until and unless the input element is out of focus.
When an element is out of focus, the browser assumes that the user is done making the change(probably the reason why onchange is fired late).
Let's see this in action. Check out the JS part here and open your console to see what is logged.
Note that onchange is fired only when input is out of focus
I am not too sure as to why in the above example onblur callback is fired after the onchange callback. We know now that onchange is fired when the element is out of focus. Know the reason?? Please comment down below.
Apart from the camel case difference the way React onChange handler works is also pretty different. It gets triggered whenever one makes a change in the input element value.
I tried to create something like React onChange. Let's have a look (not saying that this is how it works exactly).
- I had attached my custom onChange callback to the element.
- Using setter/getter to get the previously entered value and compare it with the latest one.
- Additionally attached a keyup event listener to get hold of the latest value
- Notice that the custom onChange handler gets triggered everytime a change is made.
Bye Bye !! 👋👋 Hope there were takeaways.